I'm working on a variation of a problem noted in Problem 19 Chapter 12 of the textbook "Building Java Programs". Essentially, I'm doing a recursion problem using a Fibonacci sequence. Though the program I've made works, part of the problem I'm working on is I also need to measure the time to get 45th Fibonacci number by using the implementations by 1, 2 and the one given in problem, print out how many times your implementations are faster than the one given in the problem . While I've looked at this page (Calculating a Fibonacci number with array), I was wondering is there was a way implement this without a lot of code change. This is the original method used:
public static int fibonacci (int n) {
if(n <= 2){
return 1;
} else {
return fib (n - 1) + fib(n - 2);
}
}
And this is what I've done I did the problem using two java files: one that serves as a test main class with and the other with the recursion algorithm :
PrintValues.java
import java.util.Scanner;
public class PrintValues {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number value: ");
int n = scan.nextInt();
HelperBinary.countBinary(n);
//fib(double nth);
}
}
HelperBinary.Java:
public class HelperBinary {
public static void countBinary(int n) {
if (n < 0) {
throw new IllegalArgumentException();
}
countBinary(new char[n], n);
}
private static void countBinary(char[] preFx, int n) {
if (n == 0) {
/* This is the base case
*/
System.out.println(preFx);
} else {
/* This is the "recursive" case.
*/
final int i = preFx.length - n;
/* Assign a '0' preFx and recurse
*/
preFx[i] = '0';
countBinary(preFx, n - 1);
/*Assign a '1' preFx and recurse
*/
preFx[i] = '1';
countBinary(preFx, n - 1);
}
}
}
Any help would be seriously appreciated.