C++ bootcamp · Lab 33

Power by recursion

mediumRecursion12 minLesson: Recursion

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Write long long power(int a, int b) that returns a raised to b, using recursion. Anything to the power 0 is 1.

main already reads a and b and prints the result. Do not use a loop or std::pow — recurse.

Input. Two integers a and b, with b ≥ 0.

Output. One integer: a^b.

Constraints

  • 0 ≤ b ≤ 12

Examples

Example 1
Input
2 10
Output
1024
Example 2
Input
5 0
Output
1
Hint
  1. Base case: if (b == 0) return 1;
  2. return (long long)a * power(a, b - 1);
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>

long long power(int a, int b) {
  if (b == 0) return 1;
  return (long long)a * power(a, b - 1);
}

int main() {
  int a, b;
  std::cin >> a >> b;
  std::cout << power(a, b) << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.