Unsigned long long int pow

I have the following power function that works with integers and 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 would like to have a version that allows exp> 32. Therefore, 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 does not work:

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

this will exit 0.

What is the problem with my unsigned long int implementation?

+5
source share
2 answers

Your variable is basetoo small. Change it to unsigned long long int, like the others, as it contains numbers in excess 2^32.

+5
source

Section 6.5p4 of standard C:

( ~ <, &, ^ |, ) . undefined .

6.5p5 C:

( , ), undefined.

int , . , , .

+2

All Articles