Last active
December 14, 2015 03:39
-
-
Save wfwei/5023092 to your computer and use it in GitHub Desktop.
How To Write Recursive Programs-----Don't compute anything more than once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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!!! | |
| **/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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