Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
int fun(int n) 
 {
 if (n <= 1)
 return 1;
 return fun(n-1) + fun(n-2);
 }


What I have tried:

int fun2(int n)
{
	if (n <= 1) return n;
	return fun2(n-1) + fun2(n-1);
}

time complexity for this code is:::
O(2^n)
In this code function is returning fun2(n-1) + fun2(n-1) i.e.both are same
But how to find time complexity if both are different
Posted
Updated 17-Feb-17 13:21pm

1 solution

That code look furiously like a recursive Fibonacci function.
Since the code in function is very simple, the time ans complexity mainly depend in the number of function calls.
The easiest thing to do is counting function calls.
Declare a global variable to use as counter, add a line in function that increment the value on every call.
Then collect the number of calls for each value of n, make a table with the value and compare how number of calls evolve with each n.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900