In: Computer Science
Hello there! :)
Answer 2.
You are facing the problem because of the time complexity of the algorithm you are using, that is, it takes too much time. There is a better time complexity algorithm to make it work on almost all modern machines pretty fast, that is, to find the Fibonacci number in a bottom up fashion. You know the values of and . Use them to calculate . Then use and to calculate and so on till you find . Here is a documented code to solve the assignment:
public class FibonacciTest2 {
public static long BinaryFibonacci(int k) {
if (k == 0)
return 0L; // f(0) = 0
if (k == 1)
return 1L; // f(1) = 1
// when k >= 2
long a = 0L; // f(0)
long b = 1L; // f(1)
long c = a + b; // f(2)
for (int index = 3; index <= k; ++index) {
a = b;
b = c;
c = a + b; // f(index)
}
return c; // returning f(k)
}
public static void main (String args[]) {
System.out.println(BinaryFibonacci(54));
}
}
Here is a snapshot of a demo run showing my system specs, the time to taken to run and the computed value of :
Answer 4.
This one compiles and runs just fine on my system - no issues! :)
Here's the snapshot of the run:
The program computes the binary representation of the argument integer and loops through all the characters in the generated string of bits. Since an integer has a binary representation of a size that is of the order of the logarithm of the number base two, the Big O notation runtime is .
Hope this helps! :)