This is a bit hard for me to verbalize, but I'm curious to know how to calculate the time complexity of iterating Fib(n)
times.
I have the piece of code below that will iterate through the Fibonacci numbers and subtract that amount from a given input. The loop will run n times, where n is Fib(n) > input
.
The time complexity of the code is obviously Fib(n)
but how to express that in Big-O notation?
I've read this on math exchange which if I understand correctly says that the time complexity is O(n log phi)
or about O(1.618n)
. So O(n)
?
That feels wrong though.
I've also found this other ressource for (Fibonacci formulas)[http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section6] and this one seems to say that it's actually:
i ≈ log( N ) + (log(5) / 2) / log(Phi)
The above feel like it makes more sense.
public int findTheMaximumUsingALoop(int input) {
if (input == 1 || input == 2) {
return input;
}
int count = 2;
int next = 1;
int previous = 1;
input -= next + previous;
// loop until the next Fib number is more than we have left
while (input > 0) {
int tmp = previous;
previous = next;
next = next + tmp;
input -= next;
if (input >= 0) {
count++;
}
}
return count;
}