home / study / engineering / computer science / computer science questions and a
ID: 3919048 • Letter: H
Question
home / study / engineering / computer science / computer science questions and answers / 1. write each of the following recursive methods and for each one, write a main method to test ...
Your question has been answered
Let us know if you got a helpful answer. Rate this answer
Question: 1. Write each of the following recursive methods and for each one, write a main method to test it...
1. Write each of the following recursive methods and for each one, write a main method to
test it.
(i) public static double betterPower(double x, int n)
This is an improved version of the power method that takes advantage of the following
properties:
xn = xn/2 * xn/2 for even values of n
xn = x * xn/2 * xn/2 for odd values of n
Explanation / Answer
public class BetterPower { public static double betterPower(double x, int n) { if(n == 0) { return 1; } else { double res = betterPower(x, n/2); if(n % 2 == 0) { return res * res; } else { return res * res * x; } } } public static void main(String[] args) { System.out.println(betterPower(2, 10)); System.out.println(betterPower(3, 3)); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.