首页  

Fibonacci数列第N位计算     所属分类 math 浏览量 642
为避免溢出 使用 java 里的 BigInteger
num=100000,time=587ms , length=20899
num=1000000,time=22571ms , length=208988

第10万位  计算耗时 587ms ,结果长度 20899
第100万位  计算耗时 22571ms ,结果长度 208988

代码如下

import java.math.BigInteger;

public class Fibonacci2 {
    public static void main(String[] args) throws Exception {
        // 1 1 2 3 5 8 13 21
        BigInteger f1 = new BigInteger("1");
        BigInteger f2 = new BigInteger("1");
        BigInteger f3 = null;
        int num = 1000000;
        long start = System.currentTimeMillis();
        for (int i = 0; i < num; i++) {
            f3 = f1.add(f2);
            f1 = f2;
            f2 = f3;
        }
        long end = System.currentTimeMillis();
        long time = end - start;
        // length 为 结果长度
        System.out.println("num=" + num + ",time=" + time + "ms , length=" + f3.toString().length());
    }
}

上一篇     下一篇
笛卡尔与解析几何 

勾股定理简单证明

聪明的投资者摘录

《七堂极简物理课》摘录

微积分的一些知识点

归并排序