We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<map>#include<set>#include<list>#include<cmath>#include<ctime>#include<deque>#include<queue>#include<stack>#include<string>#include<bitset>#include<cstdio>#include<limits>#include<vector>#include<climits>#include<cstring>#include<cstdlib>#include<fstream>#include<numeric>#include<sstream>#include<iostream>#include<algorithm>#include<unordered_map>usingnamespacestd;intmain(){intt;cin>>t;for(inta0=0;a0<t;a0++){longn;cin>>n;longlongintf1=1,f2=2,f=0,sum=0;while(f1<n){if(f1%2==0){sum+=f1;}f=f1+f2;f1=f2;f2=f;//cout << f1 << endl;}cout<<sum<<endl;}return0;}
Project Euler #2: Even Fibonacci numbers
You are viewing a single comment's thread. Return to all comments →
Actually it does. One can skip few steps Using this formula one will get only the even fibinoacci numbers. Traditional algo will be :
f1=1;
f2=2;
f=0;
while(f1 less than n)
{
if(f%2==0) sum+=f;
f=f1+f2;
f2=f1;
f1=f;
}
print -> sum
However you can skip the step of verifing odd-even. Also you are skiping 2 odd number and directly getting only the even numbers.
f1=2;
f2=0;
f=0;
while(f1 less than n) {
sum+=f1;
f=4*f1+f2;
f2=f1;
f1=f;
}
print -> sum
PS-Sorry for bad english
This does not change the time complexity from O(n) however.
Orignal time is something like O(3n) -> O(n)
New time complexity is something like O(2n/3) -> O(n)
LOL bro, why you've added those headers? ☻
is it working for testcase 2 and 3?? i guess not.
that code is working..do in c++ editor
wrong output