Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unsigned long long int pow

Tags:

c

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?

like image 954
DanielFetchinson Avatar asked Mar 05 '13 13:03

DanielFetchinson


People also ask

What is unsigned long long int?

Description. Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).

Is unsigned long same as unsigned long int?

They are the same type.

What is the difference between long and unsigned long?

Assuming 4 bytes, a long has the range of -2,147,483,648 to 2,147,483,647 . An unsigned long has the range of 0 to 4,294,967,295 .

Is uint64_t same as unsigned long long?

In 32-bit mode, the compiler (more precisely the <stdint. h> header) defines uint64_t as unsigned long long , because unsigned long isn't wide enough. In 64-bit mode, it defines uint64_t as unsigned long . It could have defined it as unsigned long long in both modes.


1 Answers

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

like image 178
Michał Trybus Avatar answered Sep 25 '22 23:09

Michał Trybus