Power using recursion

1

Well, I'm doing a basic code in C, I'm not very good with this language, I'm learning it, although I've already seen it not used much. It consists of doing the power operation through recursion. The problem is in the output when the power is greater than 10

// Input: // 6 20

// Output: // - 1190133760

The code:

#include <stdio.h>


int potencia(A, N){
    int x;
    if(N == 0){
    return 1;
    }

    return A*potencia(A, N-1);

}

int main(){
    int A, N;
    scanf("%d %d", &A &N);
    printf("%d\n", potencia(A, N));

}

As you can see, the output is a totally absurd number, but I do not know why or how it happens. Can someone explain to me and if possible explain what I have to do to generate the right output?

    
asked by anonymous 29.02.2016 / 22:17

1 answer

4

Your problem here is the type of variables you are using. In C , the native type int accepts values up to 2147483647 , so when you try to compute 6 ^ 15 the result does not make sense.

One solution is to use the unsigned long long int type, which accepts values between 0 and 18446744073709551615 . Your algorithm would look like this:

# include <stdio.h>

unsigned long long int potencia(unsigned long long A, unsigned long long N){
    if(N == 0){
        return 1;
    }
    return A*potencia(A, N-1);
}

int main(){
    unsigned long long int A, N;
    scanf("%llu %llu", &A, &N);
    printf("%llu\n", potencia(A, N));
}

Running it:

$ gcc main.c && ./a.out
6 20
3656158440062976

Notes: unsigned long long exists only from the C99 in . If you're running this code on an older version of C , it's worth taking a look at on this question

29.02.2016 / 22:29