Java bootcamp · Lab 37

Power by recursion

mediumRecursion12 minLesson: Recursion

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

QuestionHint and solution stay closed until you open them

Write long pow(long base, int exp). Read base exp; print result. 0 exp → 1.

Examples

Example 1
Input
2 10
Output
1024
Example 2
Input
5 0
Output
1
Hint
  1. if (exp == 0) return 1; return base * pow(base, exp-1);
Show correct code

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

import java.util.Scanner;

public class Main {
  static long pow(long base, int exp) {
    if (exp == 0) return 1;
    return base * pow(base, exp - 1);
  }
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    long base = in.nextLong();
    int exp = in.nextInt();
    System.out.println(pow(base, exp));
  }
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.