Note: I am a total beginner at c and this question was given in my university assignment.
Question: Write a function power (int a, int b), to calculate the value of a raised to b using while loop in C.
I used the following code for the hackerrank question given above:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int power(int a, int b);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int a, b, result;
scanf("%d %d", &a, &b);
result = power(a, b);
printf("%d", result);
return 0;
}
int power(int x, int y) {
int z = x;
while (y > 1) {
x *= z;
y--;
}
return x;
}
But this problem gave me errors in some of the test cases. This was easily fixed by just changing z=x to z=1, x*=z to z*=x and return (x) to return (z).
But I do not understand why my initial code was wrong.
CodePudding user response:
Using z=1 instead of z=x fixes the result for y=0.[1]
The other two changes just serve to make the code clearer, but provide no function difference.
- The results are still wrong for
y<0even with this fix. However, the function is not very useful fory<0since the best it could do is to round to0or1, usually0.
CodePudding user response:
Your code
int power(int x,int y)
{
int z=x;
while (y>1)
{
x*=z;
y--;
}
return(x);
}
Will start multiplying already with x, when none of the y was yet used for multiplication. On the other hand, using 1 would result in 1 without any multiplication and requires the first decrement of y to become x. This matches the required result of 1 for x to the power of 0.
Using z*=x repeatedly multiplies with x, which results as expected in x to the power of y (when starting with 1).
Doing x*=z results in repeated multiplication with z (which was x in your code), which seems right. But because of the need to start with 1 (see above) AND to keep the original value of x, a second variable is needed. Keeping the original value of x and storing the changing result in the new variable makes more sense than the other way round.
Returning the variable which contains the result is obvious, it just is the other variable after the change above.
Negative values of y seem to be irrelevant four your assignment. If they also need to be covered think of the result of e.g. x to the power of 2, then "undo" that, by subtracting 2 again from the exponent by dividing twice by x again. You are back at x to the power of 0. Then "undo" the same way again, i.e. divide twice again by x. The result is then x to the power of -2, i.e. 1/(x*x).
