因此,对于一个个人项目,我决定进行自己的素性测试。除了AKS测试之外,我对现有的素数测试算法没有做太多研究。我认为这对我来说太高级了,无法用Java实现,所以我自己做了。
问题在于此方法(虽然是确定性的)最多只能使用9位数字。如何更改现有代码以处理较大的输入数字?可以对此代码进行任何更改以加快速度吗? (请不要推荐全新的算法,我意识到这是一个非常基本的算法,我只想知道我是否可以对其进行改进)
public class PrimeNumberTest {
public static void main(String[] args){
//Open stream to take user input
Scanner userinput = new Scanner(System.in);
//Prompt user for input
System.out.println("Enter a number you would like to test for primality:");
//Save user input to a string var.
String inputNum = userinput.nextLine();
//Convert inputNum to a primitive int
int finalInputNum = Integer.parseInt(inputNum);
//Call method to check primality
isPrime(finalInputNum);
}
public static boolean isPrime(int finalInputNum){
//Check if the number is 2. This is an edge case
if (finalInputNum == 2){
System.out.println("It's Prime! The number has only 2 factors.");
return true;
}
//Check if number is even and not 2. Not prime
else if (finalInputNum % 2 == 0){
System.out.println("Not prime! The number has more than 2 factors.");
return false;
}
else {
/* A prime number has no more and no less than 2 factors. If even a single
other smaller number evenly divides the user inputed number, then there are
more than 2 factors, therefore not prime */
/* We use this to keep track of all number less than the input.
It starts at 1 since the input number itself is always a factor */
int numToSubtract = 1;
//Guard stops at 1 since 1 is always a factor
while ((finalInputNum - numToSubtract) > 1){
/* If the current num doesn't divide evenly with the number immediately before
it, then it's not a factor. Increment and check the next one on next loop */
if (finalInputNum % (finalInputNum - numToSubtract) != 0){
numToSubtract++;
}
else{
System.out.println("Not prime! The number has more than 2 factors.");
return false;
}
}
System.out.println("It's Prime! The number has only 2 factors.");
return true;
}
}
}