+ 6
How to make Fibonacci series on C++?
8 ответов
+ 18
http://www.sololearn.com/app/sololearn/playground/cX1b84CsDDrF/
#include <iostream>
using namespace std;
int fibonacci_rec(int i, int curr, int prev) {
if (i == 0) {return prev;}
if (i == 1) {return curr;}
return fibonacci_rec(i-1, curr+prev, curr);
}
int fibonacci(int i) {
return fibonacci_rec(i, 1, 0);
}
int main() {
int n;
cout << "Fibonacci" << endl;
cout << "Please enter a number: ";
cin >> n;
cout << n << endl;
cout << "fib(" << n << ") = " << fibonacci(n) << endl;
return 0;
}
+ 7
Here is the iterative method in case you prefer it:
int fib(int n)
{
int prev=0, curr=1, aux;
for(auto i=0; i <n; ++i)
{
aux=curr;
curr+=prev;
prev=aux;
}
return curr;
}
+ 7
Great fibonacci function, just in 3 lines!
https://code.sololearn.com/cB7CscN8bVm8/
⭐️⭐️⭐️⭐️⭐️
int fibo(int n) {
if (n <= 2)
return 1;
return fibo(n - 1) + fibo(n - 2);
}
int main() {
int whichFibo;
cin >> whichFibo;
cout << fibo(whichFibo);
return 0;
}
⭐️⭐️⭐️⭐️⭐️
+ 3
@zen personally i found this recursiv verson so elegant:)
+ 2
@zen i hav jus modified ur code...
#include <iostream>
using namespace std;
int fibonacci(int i, int curr, int prev) {
if (i == 0) {return prev;}
if (i == 1) {return curr;}
return fibonacci(i-1, curr+prev, curr);
}
int main() {
int n;
cout << "Fibonacci" << endl;
cout << "Please enter a number: ";
cin >> n;
cout << n << endl;
cout << "fib(" << n << ") = " << fibonacci(n,1,0) << endl;
return 0;
}
+ 2
lude <iostream>
using namespace std;
int main()
{
int f=0,s=1,next,i,no;
cout<<"Enter number of terms:"<<endl ;
cin >>no;
cout <<"First "<<no <<"terms of fibonacci series";
for(i=0;i<no;i++)
{
if (i<=1)
{
next=i;
}
else
{
next=f+s;
f=s;
s=next;
}
cout<< next<<endl ;
}
return 0;
}
+ 2
THX:
+ 1
#include <iostream>
using namespace std;
int fib(int n)
{
static int f1=0,f2=1,t;
if(n==0) return 0;
else {
cout<<f1<<endl;
t=f1;
f1=f2;
f2=t+f2;
n--;
return fib(n);
}
}
int main()
{
int n;
cin>>n;
cout<<"Entered no is:"<<n<<endl;
cout<<"The fibonacci series:"<<endl;
fib(n);
return 0;
}