前言
素數在信息安全領域經常被用於數據摘要或密鑰的生成算法中,爲了計算大素數也有很多的算法,本文只是通過最簡單的算法找出在Java中long數據類型所能表示的最大素數。
算法
在Java中,long 是 64 位、有符號的以二進制補碼錶示的整數;
最小值是 -9,223,372,036,854,775,808
(-2^63);
最大值是 9,223,372,036,854,775,807
(2^63 -1);
在表示時,在數字的末尾使用字母 L
或 l
表示,如 long a = 12345L
或 long 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
。