[your code here]

Jos van Uden user at domain.invalid
Sat Feb 11 08:11:40 PST 2012


On 11-2-2012 16:30, H. S. Teoh wrote:
> On Sat, Feb 11, 2012 at 12:20:22PM +0100, Jos van Uden wrote:
>> bool isKaprekar(in long n) pure nothrow
>> in {
>>      assert(n>  0, "isKaprekar(n): n must be>  0");
>>      assert(n<= uint.max, "isKaprekar(n): n must be<= uint.max");
>> } body {
> [...]
>
> Shouldn't you just use "in ulong n" as parameter instead of long with a
> contract?

Good question. I'm not sure which is better. My personal preference goes 
to (in uint n) and rely on the (self) documentation. But this is demo 
code and I wanted to show Ds support for contracts. Also, the contract 
version will at least give you a warning in debug mode. By
the way, if you use (in ulong n) you could still get in trouble
because the code only handles upto uint.max correctly due to the pow.

bool isKaprekar(in uint n) pure nothrow {
     ulong powr = n ^^ 2UL;
     ulong tens = 10, r, l;
     while (r < n) {
         r = powr % tens;
         l = powr / tens;
         if (r && l + r == n)
             return true;
         tens *= 10;
     }
     return false;
}






More information about the Digitalmars-d mailing list