Getting a negative answer after raising number to the power of x

78 Views Asked by At

I have this code that returns the answer after raising a number to an nth number.

int getPower(int base, int x){
    int result=1;

    while (x != 0) {
        result *= base;
        --x;
    }
    return result;
}

I tried testing out where base is 97 and x is 5. I get a result of -2594335. I tried changing my data type for the result to long but I'm still getting the same negative value.

1

There are 1 best solutions below

1
On

As already it was mentioned in comments to your question an object of the type int can be not large enough to be able to store such values. So substitute the type int for the type long long.

For example

#include <stdio.h>

long long int getPower( int base, unsigned int x )
{
    long long int result = 1;

    while ( x-- ) result *= base;

    return result;
}

int main( void )
{
    unsigned int x = 5;
    int base = 97;
    
    printf( "%d in the power of %u is %lld\n", base, x, getPower( base, x ) );
}

The program output is

97 in the power of 5 is 8587340257

Instead of this statement

printf( "%d in the power of %u is %lld\n", base, x, getPower( base, x ) );

you can write

long long int result = getPower( base, x );

printf( "%d in the power of %u is %lld\n", base, x, result );

An alternative approach is to use for example the float type long double instead of the integer type long long as the type of the calculated value.