欧拉计划25

The Fibonacci sequence is defined by the recurrence relation:

F n = F n−1 + F n−2, where F1 = 1 and F2 = 1.

Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

The 12th term, F12, is the first term to contain three digits.

What is the index of the first term in the Fibonacci sequence to contain 1000 digits?

#include<iostream>
#include<string.h>
using namespace std;

int a[1005],b[1005];
void add(int a[],int b[]){
	int c;
	for(int i = 1;i <= 1000;i++){
		c = a[i];
		a[i] += b[i];
		b[i] = c;
	}
	for(int j = 1;j <=1000; j++){
		if(a[j]>=10){
			a[j+1]++;
			a[j] %= 10;
		}
	}
}


int main()
{
	memset(a,0,sizeof(a));
	memset(b,0,sizeof(b));
	int temp = 2;
	a[1] = 1;
	b[1] = 1;
	while(!a[1000]){
		temp++;
		add(a,b);
	}
	for(int i=0;i<50;i++){
		cout<<a[i];
	}
	cout<<endl;
	for(int i=0;i<50;i++){
		cout<<b[i];
	}
	cout<<endl;
	cout<<temp<<endl;
	return 0;
}

更新一下做法,系统的写一写:


#include <iostream>
#include <algorithm>
#include <string.h>
#include <cmath>
using namespace std;

int f[2][1005];

int main() {
    int n = 2;
    f[1][0] =f[1][0] = f[0][1] = f[1][1] = 1;
    while ( f[n%2][0] < 1000 ) {
        n++;
        /*n0存的是当前位,n1存的是边上的n-1位,n0位没有n1位大*/
       
        int n1= !(n & 1);
        int n0 = n1 ^ 1;
        int len;
        f[n0][0] > f[n1][0] ? len = f[n0][0]:len = f[n1][0];
        for (int i = 1; i <= len; i++) {
            f[n0][i] += f[n1][i];
        }
        f[n0][0] = len;
        for (int i = 1; i <= f[n0][0]; i++) {
            if(f[n0][i] < 10) continue;
            f[n0][i+1] += f[n0][i]/10;
            f[n0][i] %= 10;
            f[n0][0] += (f[n0][0] == i);
        }
    }
    cout << n << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值