Error in recursive logic

Asked

Viewed 123 times

2

My recursive function needs to calculate the power from b to N is giving error "Segmentation failure (recorded core image)", which can be?

My job:

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;
}
  • saw this error now and correct, but when I was testing putting b=2 and expo=3, gave 16 the result, was to have given 8, q may have been?

  • A number high to 1 is equal to itself. Change the test n = 0 to n = 1.

1 answer

3


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

Now let’s check how the function should be potencia. Thinking of exponentiation recursively, using example 2 cubed:

  • 23 is the same as 2 * 22
  • 22 is the same as 2 * 21
  • 21 is the same as 2 * 20
  • 20 is equal to 1

I mean, in a generic way, we have to:

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

Therefore, your function 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 in the 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 on ideone.

Remember that using recursion for this problem is not the best solution. The best thing would be to make a simple loop to multiply the number several times (and if it is a real application and not an exercise, the ideal is to use what you already have ready).

  • 1

    Got it, thanks buddy

Browser other questions tagged

You are not signed in. Login or sign up in order to post.