java大数类

java.math.BigInteger提供的方法:

  1. BigInteger add(BigInteger other)
  2. BigInteger subtract(BigInteger other)
  3. BigInteger multiply(BigInteger other)
  4. BigInteger divide(BigIntegr other)
  5. int compareto(BigInteger other)
  6. BigInteger mod(BigInteger other)
  7. static BigInteger valueOf(long x)

    valueOf方法可以将普通的数值转换为大数值:

BigInteger a=BigInteger.valueOf(100);
  • 1
  • 1

输出febonacci数列

输出febonacci数列前100项,大约在93项时会超出long的范围:

public static void  fibonacci(){
        long[] a=new long[100];
        for(int i=0;i<100;i++){
            if(i==0){
                a[0]=0;
                System.out.print(a[i]+"\t");
                continue;
            }else if(i==1){
                a[1]=1;
                System.out.print(a[i]+"\t");
                continue;
            }
            a[i]=a[i-1]+a[i-2];
            System.out.print(a[i]+"\t");
            if((i+1)%5==0){System.out.println("");}
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

这里写图片描述 
改进:

public static void fibonacci() {
        BigInteger[] a = new BigInteger[200];
        for (int i = 0; i < 200; i++) {
            if (i == 0) {
                a[0] = BigInteger.valueOf(0);
                System.out.print(a[i] + "\t");
                continue;
            } else if (i == 1) {
                a[1] = BigInteger.valueOf(1);
                System.out.print(a[i] + "\t");
                continue;
            }
            a[i] = a[i - 1].add(a[i - 2]);
            System.out.println("第" + i + "项:\t" + a[i] + "\t");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值