Answer:
import java.util.Scanner;
public class Power
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the base and power: ");
int base = input.nextInt();
int power = input.nextInt();
System.out.println(powerRecursion(base, power));
System.out.println(powerLoop(base, power));
long startTimeRecursion = System.nanoTime();
powerRecursion(base, power);
long estimatedTimeRecursion = System.nanoTime() - startTimeRecursion;
long startTimeLoop = System.nanoTime();
powerLoop(base, power);
long estimatedTimeLoop = System.nanoTime() - startTimeLoop;
System.out.println("Recursion time: " + estimatedTimeRecursion);
System.out.println("Loop time: " + estimatedTimeLoop);
}
public static int powerRecursion(int base, int power) {
if (power != 0)
return (base * powerRecursion(base, power - 1));
else
return 1;
}
public static int powerLoop(int base, int power) {
int total = 1;
for(int i=1; i<=power; i++) {
total *= base;
}
return total;
}
}
Step-by-step explanation:
Inside the functions:
- Find the power of the numbers accordingly
Inside the main:
- Ask the user for the base and power
- Call the functions and print the results
- Calculate the number of nanoseconds that each method takes using System.nanoTime()
- Print the times