您的位置:首页 > 其它

Project Euler 002 Even Fibonacci numbers

2017-02-12 19:53 579 查看
题意:求≤4000000的所有偶fibonacci数的和

分析:依旧考虑两种做法。

1. 我们直接枚举每个斐波那契数,O(log4000000)的复杂度。

2. 考虑fib数列的奇偶性,每三个一个循环节,那我们可以设计一个矩阵乘法或者直接拿通项求一个等比数列。

#include <bits/stdc++.h>

#define ll long long

#define pii std::pair<int,int>
#define mp std::make_pair
#define fi first
#define se second

#define SZ(x) (int)(x).size()
#define pb push_back

template<class T>inline void chkmax(T &x, const T &y) {if(x < y) x = y;}
template<class T>inline void chkmin(T &x, const T &y) {if(x > y) x = y;}

template<class T>
inline void read(T &x) {
char c;int f = 1;x = 0;
while(((c=getchar()) < '0' || c > '9') && c != '-');
if(c == '-') f = -1;else x = c-'0';
while((c=getchar()) >= '0' && c <= '9') x = x*10+c-'0';
x *= f;
}
static int outn;
static char out[(int)2e7];
template<class T>
inline void write(T x) {
if(x < 0) out[outn++] = '-', x = -x;
if(x) {
static int tmpn;
static char tmp[20];
tmpn = 0;
while(x) tmp[tmpn++] = x%10+'0', x /= 10;
while(tmpn) out[outn++] = tmp[--tmpn];
}
else out[outn++] = '0';
}

int main() {
int f[100] = {0};
f[0] = f[1] = 1;
ll sum = 0;
for(int i = 2; ; ++i) {
f[i] = f[i - 1] + f[i - 2];
if(!(f[i] & 1)) sum += f[i];
if(f[i] > 4000000) break;
}
std::cout << sum << std::endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数学