Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fibonacci number fast algorithm #43

Merged
merged 1 commit into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added Programs- Coder/C++/Fibonacci series/a.exe
Binary file not shown.
27 changes: 27 additions & 0 deletions Programs- Coder/C++/Fibonacci series/fibonacci_optimised.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include <iostream>
using namespace std;
int fibonacci_naive(int n) {
if (n <= 1)
return n;

return fibonacci_naive(n - 1) + fibonacci_naive(n - 2);
}

int fibonacci_fast(int n) {
int prev = 0, next = 1, ans;
if(n==0) return prev;
for(int i=2; i<=n ; i++){
ans = prev + next;
prev = next;
next = ans;
}

return next;
}

int main() {
int n = 0;
cin >> n;
cout << fibonacci_fast(n) << '\n';
return 0;
}