Error in recursion logic

2

My recursive function needs to calculate the power of high b to N is giving error of "Segmentation fault (recorded core image)", what can be?

My role:

int potencia(int b, int n, int a){

if(n == 0){
    return b;
}

    b=b*a;

    return potencia(b,n-1,a);
}

int main(){
    int a,b,pot,n;

    printf("Informe um valor b: ");
    scanf("%d",&b);
    printf("Informe um valor expo: ");
    scanf("%d",&expo);

    a=b;
    pot=potencia(b,expo,a);
    printf("%d\n",pot);

    return 0;
}
    
asked by anonymous 28.06.2018 / 18:43

1 answer

3

First, its function does not need 3 parameters. If you want to calculate "b high to n", you only need two parameters ( b and n ).

Now let's check what the potencia function should look like. Thinking of exponentiation recursively, using as an example 2 the cube:

  • 2 3 is the same as 2 2 2
  • 2 2 is the same as 2 2 1
  • 2 1 is the same as 2 * 2 0
  • 2 0 equals 1

That is, in general, we have to:

  • 2 n is the same as 2 * 2 n - 1
  • but if n is zero, the result is 1

So your role should use these rules:

// b elevado a n
int potencia(int b, int n){
    // se n for zero, o resultado é 1
    if(n == 0){
        return 1;
    }

    // b vezes (b elevado a n-1)
    return b * potencia(b, n-1);
}

And no main :

int main(){
    int b = 2;
    int expo = 3;

    int pot = potencia(b, expo);
    printf("%d\n", pot);

    return 0;
}

The result is 8.

See this code working at ideone .

    
28.06.2018 / 19:16