斐波那契数列有以下关系:
Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
下面是前12个项:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
第十二项 F12, 是第一个含有3位数的项
找出斐波那契数列中第一个包含1000位项的各个位的和。
原题:
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn1 + Fn2, 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 first term in the Fibonacci sequence to contain 1000 digits?
解题思路:这个数列的规律就是每项等于前两项之和,考虑到最后的数有1000位,那就得用之前反复提到的大树求和的方法了,这里直接用之前的大数求和函数就可以了,代码思路比较简单,直接看代码吧:
public class Launcher {
public static void main(String[] args) {
Vector<Integer> a=new Vector<Integer>();
Vector<Integer> b=new Vector<Integer>();
Vector<Integer> c=new Vector<Integer>();
a.add(1);
b.add(1);
c.add(2);
int sum =0;
while(true){
a=plus_bigNum(b,c);
if(a.size()==1000){
break;
}
b=plus_bigNum(c,a);
if(b.size()==1000){
break;
}
c=plus_bigNum(a,b);
if(c.size()==1000){
break;
}
}
for(int i=0;i<c.size();i++){
sum+=c.get(i);
}
System.out.println(sum);
}
public static Vector<Integer> plus_bigNum(Vector<Integer> a ,Vector<Integer> b){
Vector<Integer> intNum=new Vector<Integer>();
int c=0;
int count=0;//进位数,可能取值0和1
int localNum=0;//相同位数相加后去掉进1剩下的值
for(int i=0;i<a.size(); i++){ //如果a的位数比b的多,将多的位数也储存到intNum中
c=a.get(i)+b.get(i); //相同位数相加
localNum=(c+count)%10;
count=c+count>9?1:0; //是否进位
intNum.add(localNum);
if(i==a.size()-1&&b.size()>a.size()){ //相加的两数位数不同,由于我这里由上而下加,位数多的一定在前面
for(int n=i+1;n<b.size();n++){
c=b.get(n);
localNum=(c+count) % 10;
intNum.add(localNum);
count=c+count>9?1:0;
}
}
}
if(count==1){ //如果位数相同,检测最高位最后的运算是否有进位,有进位再多生成一位数“1”
intNum.add(count);
}
return intNum;
}
}