Write a function long long power(int base, int exp) that returns base raised to exp (without using pow), and use it to answer each query.
What to build
A function that does the work, and a loop that uses it.
Requirements
- Write
long long power(int base, int exp)without usingpow. - Answer each query.
Input
The first line has q (1 ≤ q ≤ 10). Each of the next q lines has base and exp (-20 ≤ base ≤ 20, 0 ≤ exp ≤ 12).
Output
One line per query: the value of base to the power exp.
Constraints
q is from 1 to 10. The base is from -20 to 20 and the exponent from 0 to 12.
Example
Input:
2
2 10
3 0
Output:
1024
1
Why it works
Multiplying in a loop, starting from 1, gives the right answer for an exponent of 0, and long long has room for the largest result.
Examples
Example 1 · Input
2 2 10 3 0
Expected output
1024 1
Example 2 · Input
1 -2 3
Expected output
-8
Hints
Hint 1
Write long long power(int base, int exp) with a loop that multiplies exp times.
Hint 2
Anything to the power 0 is 1.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
long long power(int base, int exp) {
long long result = 1;
for (int i = 0; i < exp; i++) result *= base;
return result;
}
int main(void) {
int q;
scanf("%d", &q);
for (int k = 0; k < q; k++) {
int b, e;
scanf("%d %d", &b, &e);
printf("%lld\n", power(b, e));
}
return 0;
}