The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn?1 + Fn?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?
找到第一个1000位的斐波那契数的下标。
涉及到大数的加法。
两个string类型的数做加法,把短的那个数前面补上一定数量的‘0’使得做加法的两个数长度一致,然后从低位开始做加法。
#include <iostream> #include <string> using namespace std; string pl(string a, string b) { string res = ""; if (a.length() < b.length()) { string t = a; a = b; b = t; } int lo = a.length(); int sh = b.length(); string s(lo - sh, '0'); b = s + b; int flag = 0; for (int i = lo - 1; i >= 0; i--) { int tmp = a[i] + b[i] - '0' - '0' + flag; int low = tmp % 10; flag = tmp / 10; char a1 = low + '0'; res = a1 + res; } if (flag != 0) res = "1" + res; return res; } int main() { string s[10000]; s[1] = "1"; s[2] = "1"; for (int i = 3; i <= 10000; i++) { s[i] = pl(s[i-1], s[i-2]); if (s[i].length() >= 1000) { cout << i << endl; break; } } system("pause"); return 0; }
时间: 2024-10-05 12:08:55