Ask Question
13 April, 10:43

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.

+4
Answers (1)
  1. 13 April, 13:41
    0
    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;

    }

    }

    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
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “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, ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers