欧拉工程第25题 第一个包含1000位数字的斐波那契数列项是第几项

题目

以下是斐波那契数列的递归定义:

Fn=Fn1+Fn2,F1=1F2=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
因此第12项, F12 ,是第一个包含三位数字的项。

斐波那契数列中第一个包含1000位数字的项是第几项?

解题方法

采用java BigInteger类解题,或者自定义一个利用数组分段存储的大数类。后者的实现可以点击这里

程序

public static void solve() {
    BigInteger a = BigInteger.ONE;
    BigInteger b = BigInteger.ONE;
    BigInteger c = null;
    int i = 2;
    do {
        c = a.add(b);
        a = b;
        b = c;
        i++;
    } while (c.toString().length() < 1000);
    System.out.println(i);
}
由于20数字太大,我们需要使用BigInteger类来处理,以下是Java版本的欧拉筛: import java.math.BigInteger; public class EulerSieve { public static boolean isPrime(BigInteger n) { if (n.compareTo(BigInteger.valueOf(2)) < 0) return false; if (n.compareTo(BigInteger.valueOf(2)) == 0) return true; if (n.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) return false; int bitLength = n.bitLength(); BigInteger a = BigInteger.valueOf(2); for (int i = 0; i < bitLength; i++) { if (a.modPow(n.subtract(BigInteger.ONE), n).equals(BigInteger.ONE)) { if (!a.equals(BigInteger.valueOf(2)) && !a.equals(BigInteger.valueOf(3))) { return false; } } a = a.add(BigInteger.ONE); } return true; } public static BigInteger eulerSieve(int n) { int[] primes = new int[n + 1]; boolean[] isPrime = new boolean[n + 1]; int cnt = 0; for (int i = 2; i <= n; i++) { if (!isPrime[i]) { primes[cnt++] = i; } for (int j = 0; j < cnt && i * primes[j] <= n; j++) { isPrime[i * primes[j]] = true; if (i % primes[j] == 0) { break; } } } BigInteger num = BigInteger.valueOf(n); if (!isPrime[n]) { BigInteger phi = num.subtract(BigInteger.ONE); for (int i = 0; i < cnt && primes[i] * primes[i] <= n; i++) { if (n % primes[i] == 0) { phi = phi.divide(BigInteger.valueOf(primes[i])); phi = phi.multiply(BigInteger.valueOf(primes[i] - 1)); while (n % primes[i] == 0) { n /= primes[i]; } } } if (n > 1) { phi = phi.divide(BigInteger.valueOf(n)); phi = phi.multiply(BigInteger.valueOf(n - 1)); } return phi; } else { return num.subtract(BigInteger.valueOf(1)); } } public static void main(String[] args) { BigInteger num = new BigInteger("12345678901234567890"); if (num.isProbablePrime(10)) { System.out.println(num + " is prime."); } else { BigInteger phi = eulerSieve(num.intValue()); if (phi.gcd(num).equals(BigInteger.ONE)) { System.out.println(num + " is prime."); } else { System.out.println(num + " is not prime."); } } } } 在main方法,我们可以将要判断的数转化为BigInteger类型,然后使用isProbablePrime方法进行快速判断,如果不是质数,则使用欧拉筛来进一步判断。如果欧拉函数与该数的最大公约数为1,则该数为质数,否则不是。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值