找到Java中长整型(long)所能表示的最大素数: 9223372036854775783

前言

素数在信息安全领域经常被用于数据摘要或密钥的生成算法中,为了计算大素数也有很多的算法,本文只是通过最简单的算法找出在Java中long数据类型所能表示的最大素数。

算法

在Java中,long 是 64 位、有符号的以二进制补码表示的整数;
最小值是 -9,223,372,036,854,775,808(-2^63);
最大值是 9,223,372,036,854,775,807(2^63 -1);
在表示时,在数字的末尾使用字母 Ll 表示,如 long a = 12345Llong b = 54321l,但是由于"l"容易与数字"1"混淆,不易区分,所以推荐使用大写的 L 表示。
我们在查找时,从最大值开始,只比对所有的奇数,每次减少2,直到找到为止。而查找方法使用的是逐个比较法,即将待判断的数 n 与在 [2, sqrt(n)] 范围内的所有整数逐个取余计算。

实现代码

public class DHTest {

	public static void main(String[] args) throws Exception { 
		long n =  9_223_372_036_854_775_807L;
		while (true) {
			if (is_prime(n)) {
				println("n = ", n);
				break;
			}
			n -= 2;
		}
		println("done");
	}
 
	static boolean is_prime(long n) {
		int count = 0;
		boolean isPrime = true;
		long limit = (long) Math.sqrt(n);
		for (long i = 2; i < limit + 1; i++) {
			count ++;
			if (n % i == 0) {
				isPrime = false;
				break;
			}
		}
		System.out.println((isPrime ? "O" : "X") + ", tests = " + count + ", limit = " + limit);
		return isPrime;
	} 
}	

结果

X, test count = 6, limit = 3037000499
X, test count = 4, limit = 3037000499
X, test count = 2, limit = 3037000499
X, test count = 156, limit = 3037000499
X, test count = 16, limit = 3037000499
X, test count = 2, limit = 3037000499
X, test count = 4, limit = 3037000499
X, test count = 6, limit = 3037000499
X, test count = 2, limit = 3037000499
X, test count = 10, limit = 3037000499
X, test count = 12, limit = 3037000499
X, test count = 2, limit = 3037000499
O, test count = -1257966798, limit = 3037000499
n = 9223372036854775783
done

通过以上计算,我们可以找到Java中 long 所能表示的最大素数为 9,223,372,036,854,775,783

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章