Java 欧拉工程 第二十五篇【1000位斐波那契数】

题目是:

斐波那契数列有以下关系:

Fn = Fn−1 + Fn−2, 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 = 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 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;  
            }  

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值