1

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
rinrin
  • 49
  • 5
  • `97**5` is 8,587,340,257 and it exceeds typical limit of `int` 2,147,483,647 (`2**31 - 1`). `long` may have the same size as `int`, depending on the environment. Try `long long` or `int64_t` (defined in `stdint.h`). – MikeCAT Apr 23 '21 at 14:48
  • @MikeCAT No luck. I still get the same negative answer. – rinrin Apr 23 '21 at 14:49
  • How did you "still get the same"? Did you replace *both* the return value type *and* the intermediate variable type (i.e. `int64_t getPower` and `int64_t result`)? – iBug Apr 23 '21 at 14:51
  • @iBug Yes. I changed the return type of my getPower and result. The catcher variable in my main also has a long long data type. – rinrin Apr 23 '21 at 14:53
  • @rinrin Are you printing the result with the `%lld` format specifier? – dbush Apr 23 '21 at 14:56
  • OK then how did you print it? Using the correct format specifier (`%lld` for long long or `%I64d` for `int64_t` (not Windows-compatible))? – iBug Apr 23 '21 at 14:56
  • 1
    @iBug `"%" PRId64` for `int64_t` – MikeCAT Apr 23 '21 at 14:59
  • 1
    The correct conversion specifier for `int64_t` is the string literal to which the macro `PRId64` from `` expands. – Humm Apr 23 '21 at 15:02

1 Answers1

6

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335