所以我尝试制作一个java程序来获得唯一的威尔逊素数;具有这种特征:" {[(n-1)!+ 1] / n}%n = 0"。程序类型有效,但当我输入1000时,它只能达到13号(例如另一个威尔逊素数为563)。这就是我到目前为止所拥有的。
package again;
import java.util.Scanner;
public class AGAIN
{
public static void main(String[] args)
{
Scanner lol = new Scanner(System.in);
System.out.println("Write a number.");
int n = 1;
long r;
long g;
for (long u = lol.nextInt(); u >= n; u--)
{
long s = 1;
for (r = u - 1; r >= 1; r--)
{
s = s * r;
}
if ((s + 1) % u == 0)
{
g = (s+1) / u;
if (g % u == 0)
{
System.out.printf(u + " ");
}
}
}
}
}
为什么不向我显示任何更大的数字?请帮忙!
答案 0 :(得分:1)
您要求您的程序计算(u == 563
)数量562 !,根据Windows计算器,大约是1.12806 * 10 ^ 1303。这太大了,不适合long
,其最大值为9223372036854775807
(大约9 quintillion)。
正在发生溢出,并且您没有使用您认为的数字。可以存储在long
而没有溢出的最大因子是20!,即2432902008176640000
。 (计算21!作为long
产生-4249290049419214848
,溢出是显而易见的。)
您需要使用BigInteger
来计算和存储一个巨大的数字。
答案 1 :(得分:-1)
public static String runx(BigInteger inval)
{
BigInteger theval = inval;
BigInteger calc = new BigInteger("1");
BigInteger total = new BigInteger("0");
String result = "";
for (BigInteger x = BigInteger.ONE; x.compareTo(theval.subtract(BigInteger.ONE)) == -1 ; x = x.add(BigInteger.ONE))
{
calc = ((calc.multiply(x.add(BigInteger.ONE))));
//System.out.println("Loop " + x);
}
total = calc.add(BigInteger.ONE);
if((total.mod(theval).compareTo(BigInteger.ZERO)==0))
{
if (((total.divide(theval)).mod(theval)).compareTo(BigInteger.ZERO)==0)
{
result = theval + " is prime and Wilson";
}
else
{
result = theval + " is prime");
}
}
else
{
result = theval + " is not prime");
}
return result;
}