160k views
5 votes
Write a class that will contain: 1.) a recursive method that will calculate any base to any power 2.) call the recursive method from main, asking the user for the base and the power 3.) write the loop version of the method 4.) call the loop version from main, using the same base and power that the user supplied earlier 5.) check that both methods return the same answer 6.) measure the number of nanoseconds that each method takes, & report which version of the methods is faster. Use either System.currentTimeMillis() or System.nanoTime() to get the start and end time assigned to 2 long variables, then subtract, and that is your total time.

User Joaumg
by
5.4k points

1 Answer

7 votes

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

User Andresch Serj
by
5.4k points