Java math未返回预期值
根据,如果^n-1不等于1 mod n,则该数字为复合数。我们知道,3是质数,而9不是。我的Java技能已经过时了,我可能忘记了一些非常简单的东西。请记住,这也只是测试的开始,而不是测试的完整实现。下面的示例代码对于这两个数字都返回false,而只有9应该返回falseJava math未返回预期值,java,math,random,integer,modulo,Java,Math,Random,Integer,Modulo,根据,如果^n-1不等于1 mod n,则该数字为复合数。我们知道,3是质数,而9不是。我的Java技能已经过时了,我可能忘记了一些非常简单的东西。请记住,这也只是测试的开始,而不是测试的完整实现。下面的示例代码对于这两个数字都返回false,而只有9应该返回false import java.util.Random; import java.util.Scanner; public class LucasTest { private static int n; private
import java.util.Random;
import java.util.Scanner;
public class LucasTest
{
private static int n;
private static boolean primeResult;
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static boolean isPrime(int num)
{
int a = randInt(2, num - 1);
int b = num - 1;
double c = Math.pow(a,b);
if (c != (1.0 % num)) {
return false;
}
return true;
}
public static void main(String args[])
{
System.out.println("Enter an integer:");
Scanner pNum = new Scanner(System.in);
n = pNum.nextInt();
primeResult = isPrime(n);
System.out.println("Number is likely prime?: " + primeResult);
}
}
问题出在iPrime方法的测试中 改变
if (c != (1.0 % num))
到
你要做的是首先取1.0 mod num,它是1,然后检查c是否不等于1,除了num=1,它永远不会等于1
我们需要做的是计算c mod num,然后检查它是否为1
我用这个更改测试了您的代码,它正确地将3、7和13标识为prime,将9和15标识为composite
注意:该定理中有两个检查,您只实现了第一个检查。因此,您可能会随机返回复合数字的true语句。此外,该定理指出,对于给定的数字,某些a必须存在,但并非每个a的条件都为真,因此,即使使用这两种检查,当您测试随机a时,您也可以随机将素数识别为复合数
要完全实现这个定理,你必须实现第二个条件,然后检查区间1,n中的每个a。如果这两个条件都适用于任何给定的a,则返回true,不必检查其他a,否则返回false。当然,第二个条件更难实现,因为您必须找到n-1的主要因子。您共享的页面中的伪代码说 输入:n>2,测试素性的奇数整数;k、 决定测试准确性的参数 输出:如果n为素数,则为素数,否则为复合或可能为复合; 确定n的素因子−一,
LOOP1: repeat k times:
pick a randomly in the range [2, n − 1]
if a^(n-1) != 1 (mod n) then return composite
otherwise
LOOP2: for all prime factors q of n−1:
if a^((n-1)/q) != 1 (mod n)
if we did not check this equality for all prime factors of n−1
then do next LOOP2
otherwise return prime
otherwise do next LOOP1
return possibly composite.
你在IDE调试器中跟踪代码了吗?我不确定在这种情况下我会相信Math.pow,而不是你必须自己编写的实际整数幂mod n方法。我现在使用的是BlueJ,Jim,调试器似乎没有输出任何对我有用的东西。我不知道你期望1 mod num是什么。如何在没有任何循环的情况下检查素数?我想你得重新研究一下这个公式。是的,我意识到了错误。凌晨1点的作品。另外,我之前说过这只是一个开始。编辑:你上次的编辑纠正了我愚蠢的错误。非常感谢你!这个问题已经回答了,我完全意识到这一点,因为我是基于这个赤裸裸的开始。从那时起,我已经克服了这一点。不过,谢谢你。
LOOP1: repeat k times:
pick a randomly in the range [2, n − 1]
if a^(n-1) != 1 (mod n) then return composite
otherwise
LOOP2: for all prime factors q of n−1:
if a^((n-1)/q) != 1 (mod n)
if we did not check this equality for all prime factors of n−1
then do next LOOP2
otherwise return prime
otherwise do next LOOP1
return possibly composite.