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).
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?
– flavio
A number high to 1 is equal to itself. Change the test n = 0 to n = 1.
– Lisângelo Berti