cmathintegerlong-integerexponentiation

unsigned long long int pow


I have the following power function which operates on integers and it works fine:

int ipow( int base, int exp )
{
    int result = 1;
    while( exp )
    {
        if ( exp & 1 )
        {
            result *= base;
        }
        exp >>= 1;
        base *= base;
    }
    return result;
}

Now I'd like to have a version which allows exp > 32. So I use unsigned long long ints:

unsigned long long int ipow( int base, int exp )
{
    unsigned long long int result = 1ULL;
    while( exp )
    {
        if ( exp & 1 )
        {
            result *= (unsigned long long int)base;
        }
        exp >>= 1;
        base *= base;
    }
    return result;
}

But this second version doesn't seem to work:

unsigned long long int x;
x = ipow( 2, 35 );
printf( "%llu\n", x );

this will output 0.

What's the problem with my unsigned long long int implementation?


Solution

  • Your base variable is too small. Change it to unsigned long long int, like the others, since it holds numbers greater than 2^32.