Skip to content

Instantly share code, notes, and snippets.

@wfwei
Last active December 14, 2015 03:39
Show Gist options
  • Select an option

  • Save wfwei/5023092 to your computer and use it in GitHub Desktop.

Select an option

Save wfwei/5023092 to your computer and use it in GitHub Desktop.
How To Write Recursive Programs-----Don't compute anything more than once
long int Fib(int N){
if(N<=1)
return 1;
else{
return Fib(N-1)+Fib(N-2);
}
}
/**
running time of Fib(N):
T(N) = T(N-1) + T(N-2) +2 > (3/2)^N (N>4)
exponentially!!!as bad as possible...
Notice:
line5: Fib(N-1) acturally computes Fib(N-2), but Fib(N-2) recomputes!!!
**/
long int Pow(long int X, unsigned int N){
if(N==0)
return 1;
else if(N==1)
return X;
else if(N%2==0)
return Pow(X*X, N/2); // Should not be: return Pow(X, N/2)*Pow(X, N/2);
else
return Pow(X*X, N/2)*X;
}
/**
running time is no longer than O(logN)
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment