Created
February 14, 2013 17:54
-
-
Save ashwch/4954691 to your computer and use it in GitHub Desktop.
Calculate Nth Fibonacci number using DP.
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
| #include <iostream> | |
| using namespace std; | |
| long double fibo_dp(long double); | |
| int main(void){ | |
| long double n; | |
| cout <<"enter number :"; | |
| cin >> n; | |
| cout <<fibo_dp(n)<<endl; | |
| return 0; | |
| } | |
| long double fibo_dp(long double n){ | |
| long double first,second,current; | |
| first=0; | |
| second=1; | |
| if (n==1) {return first;} | |
| else if (n==2) {return second;} | |
| while ((n-2)>0){ | |
| current=first+second; | |
| first=second; | |
| second=current; | |
| n--; | |
| } | |
| return current; | |
| } |
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
| def fibo_dp(n): | |
| first,second=0,1 | |
| if n==1: | |
| return first | |
| if n==2: | |
| return second | |
| for _ in xrange(n-2): | |
| new=first + second | |
| first=second | |
| second=new | |
| return new |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment