0
Challenge.... A fibonacci series using 2 variables exactly?
7 Antworten
+ 1
In which language?
+ 1
The optimized way is starting with the first values of the serie and storing the values of the last two Fibonacci numbers calculated.
http://code.sololearn.com/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;
}
+ 1
It's a bit of a shame that the 2-variable limit prevents you from using the optimized version. This version keeps recalculating the lower terms of the serie.
http://code.sololearn.com/cWOothBAImcz
#include <iostream>
using namespace std;
int fibonacci(int i) {
if (i == 0)
return 0;
if (i == 1)
return 1;
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
cin >> i;
cout << fibonacci(i);
return 0;
}
0
C++
0
What is the optimised way
0
http://www.sololearn.com/app/cplusplus/playground/cUgIyY0KHi7z/
optimized a little bit.
you can improve it by using memoization.
#include <iostream>
using namespace std;
//fibo(0) = 0, fibo(1) = 1
int fibonacci(int n) {
if (n <= 1) return n;
//when n is odd
else if (n & 1) {
int k = (n+1)/2;
return fibonacci(k-1)*fibonacci(k-1)+fibonacci(k)*fibonacci(k);
} else {
int k = n/2;
return fibonacci(k)*(2*fibonacci(k-1)+fibonacci(k));
}
}
int main() {
int n;
cin >> n;
cout << fibonacci(n) << endl;
return 0;
}
0
#include <iostream>
using namespace std;
int main ()
{
int x = 0;
int y = 1;
while (y<1000)
{
cout << x << endl;
y += x;
cout << y << endl;
x += y;
}
return 0;
}