Number of calls for nth Fibonacci number - c++

Consider the following code snippet:
int fib(int N)
{
if(N<2) return 1;
return (fib(N-1) + fib(N-2));
}
Given that fib is called from main with N as 10,35,67,... (say), how many total calls
are made to fib?
Is there any relation for this problem?
PS: This is a theoretical question and not supposed to be executed.
EDIT:
I am aware of other methods for the faster computation of Fibonacci series.
I want a solution for computing number of times fib is invoked for fib(40),fib(50) ,.. without the aid of compiler and in exam condition where you are supposed to answer 40 question similar to this one in a stipulated of time ( about 30 mints).
Thanks,

Let f(n) be the number of calls made to calculate fib(n).
If n < 2 then f(n) = 1.
Otherwise, f(n) = 1 + f(n - 1) + f(n - 2).
So, f is at least O(fib(n)). In fact, f(n) is 2 * fib(n) - 1. We show this by induction:
Base cases (n < 2, that is, n = 0 or n = 1):
f(n) = 1 = 2 * 1 - 1 = 2 * fib(n) - 1.
Induction step (n >= 2):
f(n + 1) = f(n) + f(n - 1) + 1
f(n + 1) = 2 * fib(n) - 1 + 2 * fib(n - 1) - 1 + 1
f(n + 1) = 2 * fib(n + 1) - 1
There exist efficient ways to calculate any Fibonacci term. Thus the same holds for f(n).

Is there any relation for this problem
?
There is a close-form equation for the nth fibonacci number: http://en.wikipedia.org/wiki/Fibonacci_number#Closed_form_expression
In the pseudocode you posted, the number of calls satisfies the recurrence relation
x(n) = x(n-1) + x(n-2) +1 # for n>=2
x(1) = 1
x(0) = 1
This is almost same as the Fibonacci recurrence relation. Proof by induction can show that the number of calls to fib made by fib(n) is equal to 2*fib(n)-1, for n>=0.
Of course, the calculation can be sped up by using the closed form expression, or by adding code to memorize previously computed values.

As mentioned above, you need to solve the following recurring equation:
K(n)=K(n-1)+K(n-2)+1
Let's write it for n-1: K(n-1)=K(n-2)+K(n-3)+1
Now, subtract the second one from the first one:
K(n)-K(n-1) = K(n-1) - K(n-3),
or
K(n) - 2*K(n-1) + K(n-3) = 0.
The respective characteristic equation will be:
x^3 - 2*x^2 + 1 = 0.
It has the following roots: 1, (1+sqrt(5))/2, (1-sqrt(5))/2
Thus for any real A,B,C the following function
K(n) = A*(1)^n + B*((1+sqrt(5))/2)^n + C*((1-sqrt(5))/2)^n
will be a solution for your equation.
To find A,B,C you need to define several initial values K(0), K(1), K(2) and solve the system of equations.

phi is a constant
position = ceil(log((n - 0.5)*sqrt(5))/log(phi));
n is the fibonacci number...
position will give you the which fibonacci number is n
for example given 13 , position will be 7 - 0 1 1 2 3 5 8 13
using this position just calculate the fibonacci number at position-1 or any position you want relative to given fibonacci number.
Previous Fibo Num = floor((pow(phi,position-1)/sqrt(5))+0.5);
floor((pow(phi, position)/sqrt(5))+0.5) - is the standard formula for calculating Nth fibonacci num (Note - This is not an approximation)
I have just reverse this formula to calculate the position and use the position - 1 to calculate the previous fibonacci number.
Ref - http://itpian.com/Coding/20951-Given-the-Nth-fib-no-and-find-the--N-1-th-fib-number-without-calculating-from-the-beginning---------.aspx

This is a classic problem for solving with Recurrence Relations.
Specifically, the fibonacci problem has the following parameters:
f(0) = 1
f(1) = 1
f(n) = f(n-1) + f(n-2)
Once you master solving recurrences, you'll have no problem reaching the solution (which, incidently, is exactly the same as fib(n)).

Interesting question, I can't give you a formula, but I wrote a Ruby program to do it, it works on numbers I figured out on paper, and it should work for any.
#!/usr/bin/ruby
#find out how many times fib() would need to be called
def howmany(n)
a = [ ]
a.push n-1
a.push n-2
while a.select{|n| n > 2}.length > 0
a.map! do |n|
n > 2 ? [n-1,n-2] : n
end
a.flatten!
end
a.length
end
.
>> howmany(10)
=> 55
It's slow.. I'm figuring out 35 right now, I'll edit when it finishes.
Edit:
>> howmany(35)
=> 9227465

Related

Big O for an algorithm for finding prime numbers [duplicate]

This question already has answers here:
What is a plain English explanation of "Big O" notation?
(43 answers)
Closed 5 years ago.
I have a pseudo code from university:
(0) initialize logic array prim[ n ]
(1) prim[ 1 ] = false
(2) for i = 2 to n do
(3) for k = 2 to i − 1 do
(4) if i % k == 0 then
(5) break
(6) prim[i] = (k == i) // Was loop (3) fully executed?
(7) return prim[]
Now I have to calculate the Big O for this pseudo code.
We learnt to make it step by step, by adding up the number of operations.
This is what I got so far:
Comparisons:
(4): (n-1)(n-2) outer loop * inner loop
(6): (n-1) outer loop
(4) + (6): n^2 - 2 n + 1 operations for all comparisons
Assignments:
(1): 1
(6): (n - 1)
(1) + (6): n operations for all assignments
Division:
(4): (n-1)(n-2) outer loop * inner loop
n^2 - 3 n + 2 operations for the division.
So if you add up those numbers:
(n^2 - 2 n + 1) + n + n^2 - 3 n + 2 = 2n^2 - 4 n + 3
I think there is somewhere a misconception from my side, because the Big O should be O(n^2) but here it is O(2n^2) from what I understand.
Can you guys please help me figuring out, what my misconception is. Thanks
Your misconception is thinking that 2n^2 is not O(n^2). Big-O ignores scaling constants, so you can ignore the 2 out front.
Calculation of the inner loop is wrong:
When the outer loop (i) goes from 2 to n then the innerloop wil iterate no more then 0 + 1 + 2 + ... + n-2 times, which equals to the sum of the first n-2 natural numbers.
The formula for the sum of the first n natural numbers is n*(n+1)/2.
Since there is a -2 offset the maximum number of iterations of the innerloop would be (n-2) * (n-1) / 2.
Actually you've already got the correct answer!
Thats because O(2*n²) equals O(n²). Constants multiplicators don't affect Big-O. For more information on the math behind it I recommend reading about Asymptotic Analisys. To keep it simple, it has to do with when the n tends to infinity.

Dynamic Programming solution for a Recursion solution

Given an input n , find the sum of all the possible combinations of numbers 1 ... n.
For example, if n=3 , then all the possible combinations are
(1),(2),(3),(1,2),(1,3),(2,3),(1,2,3)
and their sum is
1 + 2 + 3 + (1+2) + (1+3) + (2+3) + (1+2+3) =24
I am able to solve this problem using recursion. How can I solve this problem using Dynamic Programming ?
#include<iostream>
using namespace std;
int sum=0,n;
int f(int pos,int s)
{
if(pos>n)
{
return 0;
}
else
{
for(int i=pos+1;i<=n;++i)
{
sum+=s+i;
f(i,s+i);
}
}
}
int main()
{
cin>>n;
sum=0;
f(0,0);
cout<<sum<<'\n';
}
}
EDIT
Though this problem can be solved in constant time using this series.
But I want to know how this can be done using Dynamic Programming as I am very weak at it.
You do not need to use dynamic programming; you can use simple arithmetic if you want.
The number of cases is 2 ^ n, since each number is either on or off for a given sum.
Each number from 1 to n is used in exactly half of the sums, so each number comes 2 ^ (n-1) times.
1 + 2 + ... + n = (n - 1) * n / 2.
So the sum is (n - 1) * n / 2 * 2 ^ (n-1).
For n = 3, it is (4*3/2) * 4 = 24.
EDIT: if you really want to use dynamic programming, here's one way.
Dynamic programming makes use of saving the results of sub-problems to make the super problem faster to solve. In this question, the sub-problem would be the sum of all combinations from 1 ... n-1.
So create a mapping from n -> (number of combinations, sum of combinations).
Initialize with 1 -> (2,1). Because there are two combinations {0,1} and the sum is 1. Including 0 just makes the math a bit easier.
Then your iteration step is to use the mapping.
Let's say (n-1) -> (k,s), meaning there are k sets that sum to s for 1 ... n-1.
Then the number of sets for n is k * 2 (each combination either has n or does not).
And the sum of all combinations is s + (s + k * n), since you have the previous sum (where n is missing) plus the sum of all the combinations with n (which should be k * n more than s because there are k new combinations with n in each).
So add n -> (2*k,2*s + k*n).
And your final answer is the s in n -> (k,s).
let dp[n] be the result, Therefore:
dp[1] = 1
dp[n] = 2 * dp[n-1] + 2^(n-1) * n
First, it is obvious that dp[1] = 1
Second, dp[n] is the sum which contains n and sum which didn't contains n
E.G: dp[3] = {(1) (2) (1,2)} + {(3), (1,3), (2,3), (1,2,3)}
We can find dp[n-1] appear twice and the number of n appear 2^(n-1) times
I think maybe it is what you want.

Recursive Fibonacci algorithm with variant

I've implemented a traditional fibonacci recursion related with the reproduction of a population of rabbits in python2.7
def fibonacci(n):
if n is 0 or n is 1: return 1
else: return (fibonacci(n-1)+fibonacci(n-2))
This code computes the population if exactly one month after two rabbits mate, they produce one male and one female rabbit. Now I need to modify the code to compute the population if every pair of reproduction-age rabbits produces a litter of k rabbit pairs (instead of only 1 pair). How can I do this in a recursive way? What is the most appropriate model for the recursive case?
Well let's try and derive the sequence, which is also known as a multi-nacci sequence of order k. See this paper for some more interesting tidbits.
The basic rule is the same: it takes 1 month to for a pair to mature
Therefore at:
Month 0: 1 pair exists (young)
Month 1: 1 pair exists (adult)
Month 2: 1 pair exists (adult) + k pairs exist (young) = 1 + k total
Month 3: 1 + k pairs exist (adult) + k pairs exist (young) = 1 + 2k total
Month 4: 1 + 2k pairs exist (adult) + k (1 + k) pairs exist (young) = 1 + k(3 + k) total
Month 5: 1 + 3k + k^2 pairs exist (adult) + k (1 + 2k) pairs exist (young) = 1 + k(4 + 3k) total
and so on...
Notice that with each month, the total number of rabbit pairs is k * number of adults (which are two generations old) + number of young pairs (which are 1 generation old). Therefore the amount of rabbits at generation n is k * number of rabbits at generation n - 2 (as these are now all adults) + number of rabbits at generation n - 1
Mathematically: f(0) = 1, f(1) = 1, f(n) = f(n-1) + k * f(n-2).
Code:
def fibnum(n, k):
if n < 0:
raise ValueError("n must be a positive value")
if n is 0 or n is 1:
return 1
else:
return (fibnum(n-1, k) + k * fibnum(n-2, k))
Notes:
This code is 0-based: so 5th month is n=4 and so on.
WARNING: this sequence grows ridiculously fast with larger k (so calculating fibnum(100, 100) may take a while). Memoization is advised to provide a significant speedup for increasing n.
Update: Changed code to accept k as a parameter, and cleaned up my code formatting a bit. Added reference to multinacci sequence

Writing and solving a recurrence that counts the number of multiplications in this code?

Let M(n) be the number of multiplications that the function fct does.
//precondition: n>0
int fct (const int A[], int n) {
if (n==1)
return A[0]*A[0];
else return A[n-1] * fct(A,n-1) * A[n-1];
}
write recurrence relation for M(n) where n is the number of elements in the array
Solve the recurrence relation to obtain M(n) in terms of n
Write the resulting expression of part 2 in big O notation
So this was a quiz, and I have the answer key, but not too sure how this was computed, M(n)=2n-1 with O(n)..I do not know how this was determined, can someone explain? Thanks
Let's look at what each call does. Each call, when n > 1,
Does exactly two multiplications, then
Makes a recursive call on a problem of size n - 1
Therefore, we can write the recurrence as
M(1) = 1
M(n) = 2 + M(n-1)
If you use the iteration method, you'll notice this pattern:
M(1) = 1
M(2) = M(1) + 2 = 3
M(3) = M(2) + 2 = 5
M(4) = M(3) + 2 = 7
...
M(n) = 2n - 1
Now that you have this, you can write it asymptotically as M(n) = Θ(n).
Hope this helps!

Sum of products of Fibonacci numbers [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
Given a series
Fib(1) * Fib (n+2) + Fib(2) * Fib(n+1) + Fib(3) * Fib(n) + ...... + Fib(n-1) * Fib(4)
or Summation Fib(x) * Fib (n-x+3) where x varies from 1 to n-1
where Fib(n) is nth number of Fibonacci series
to evaluate this series Fib(n) can be calculated using matrix exponentiation .
But the complexity for this is logn and for the n terms it would be nlogn .
I want this series to get reduced to a single term or some other optimization to improve *the time complexity .*
Any suggestions ??
I can't reduce the sum to a single term, but it can be reduced to a sum of five terms, which reduces the complexity to O(log n) arithmetic operations.
However, Fib(n) has Θ(n) bits, so the number of bit-operations is not logarithmic. There is a multiplication of a number the size of Fib(n) with n-1, so the number of bit-operations is M(n,log n), where M(a,b) is the bit-operation complexity of a multiplication of an a-bit number with a b-bit number. For the naive algorithm, M(a,b) = a*b, so the number of bit-operations in the below algorithm is O(n*log n).
The fact that allows this reduction is that Fibonacci numbers (like all numbers in a sequence defined by a linear recurrence) can be written as the sum of pure exponential terms, in particular
Fib(n) = (α^n - β^n) / (α - β)
where
α = (1 + √5)/2; β = (1 - √5)/2.
In addition to the Fibonacci numbers, I also use the Lucas numbers, which follow the same recurrence as the Fibonacci numbers,
Luc(n) = α^n + β^n
so the sequence of Lucas numbers (starting from index 0) begins with
2 1 3 4 7 11 18 29 47 ...
The relation Luc(n) = Fib(n+1) + Fib(n-1) allows an easy conversion between Fibonacci and Lucas numbers, and computation of Luc(n) in O(log n) steps can reuse the Fibonacci code.
So with the representation of Fibonacci numbers given above, we find
(α - β)^2 * Fib(k) * Fib(n+3-k) = (α^k - β^k) * (α^(n+3-k) - β^(n+3-k))
= α^(n+3) + β^(n+3) - (α^k * β^(n+3-k)) - (α^(n+3-k) * β^k)
= Luc(n+3) - ((-1)^k * α^(2k) * β^(n+3)) - ((-1)^k * α^(n+3) * β^(2k))
using the relation α * β = -1.
Now, since α - β = √5 the summation k = 1, ..., n-1 yields
n-1 n-1 n-1
5 * ∑ Fib(k)*Fib(n+3-k) = (n-1)*Luc(n+3) - β^(n+3) * ∑ (-α²)^k - α^(n+3) * ∑ (-β²)^k
k=1 k=1 k=1
The geometric sums can be written in closed form, and a bit of juggling yields the formula
n-1
∑ Fib(k)*Fib(n+3-k) = [5*(n-1)*Luc(n+3) + Luc(n+2) + 2*Luc(n+1) - 2*Luc(n-3) + Luc(n-4)]/25
k=1
Steps to follow:
Define std::vector<int> and fill it with all fibonacci numbers which you need. Compute these numbers using dynamic programming; that is, make use of results which you already have computed. Don't compute the same value more than once!
Once you have the vector filled with all the numbers you need, apply the formula Fib(x) * Fib (n-x+3) in a loop and compute the sum of the products.
assuming f(n)=f(n-1)+f(n-2) for n>2 and f(1)=f(2)=1, f(0)=0
Let E(n)=sum(k=1 .. n-1, f(k)f(n-k+3)) and E'(n)=sum(k=0 .. n, f(k)f(n-k))
Clearly E(n)=E'(n+3) - ( f(0)f(n+3) + f(n)f(3) + f(n+1)f(2) + f(n+2)f(1) + f(n+3)f(0) )
On wolfram you'll find : E'(n)= (nL(n)-f(n))/5, with L(n)=f(n+1)+f(n-1)
from this :
5E(n)=(n+3)( f(n+4)+f(n+2) ) - 5(2f(n) + f(n+1) +f(n+2))
5E(n)=(n+3)( 4f(n+1)+3f(n) ) - 10f(n+1) -15f(n)
5E(n)= (4n+2)f(n+1) + (3n-6)f(n)
Should be simple to evaluate, the complexity should be the same as the fibonnaci algorithm used,
If I know what a Lucas number is, then I can use the identity...
F(n)*F(m) = [L(m+n) - (-1)^n*L(m-n)]/5
See this reduces the sum of products of Fibonacci numbers into a sum of Lucas numbers.
Even better, since n+m is constant for each term, the sum reduces further. There are n-1 terms in this sum, so the sum reduces to a sum of Lucas numbers.
[(n-1)*L(n+3) + L(n+1) - L(n-1) + L(n-3) - ... + (-1)^(n-1)*L(5-n)]/5
As a test, for n = 5, I get 40, which is consistent with the direct sum of products:
1*13 + 1*8 + 2*5 + 3*3 = 40
For n = 1000, I get a sum of:
82283375600539014079871356568026158421560221654785733943009487102720
211767741849325389562067921531531130739623611293922046989610820831567088
516047002196966545744637588824274730947688693969572937880383134671205375
Even better, some extra work will let that sum of Lucas numbers contract further since the Lucas numbers of negative index have a simple relation to those with positive index.
As far as computing the k'th Lucas (as well as the k'th Fibonacci) number, it can be done quite efficiently as shown here.