[英]Basic Java - Finding if a number is a prime number using while loop
I have a question regarding an answer that was given here a while ago.我有一个关于不久前在这里给出的答案的问题。
I came up with the same answer myself in the code attached but I'm trying to understand why do I need to divide the input number by 2 (line 10), and not just let the loop run its course till the value of the input number achieved.我自己在附加的代码中提出了相同的答案,但我试图理解为什么我需要将输入数字除以 2(第 10 行),而不仅仅是让循环运行直到输入的值达到的数量。
1 import java.util.Scanner;
2 public class numIsPrime {
3 public static void main(String[] args) {
4 Scanner sc = new Scanner(System.in);
5 int i = 2;
6 boolean isPrime = true;
7 System.out.println("Enter a number");
8 int num = sc.nextInt();
9
10 while (i < num ) // (i <= num / 2)
11 {
12 if (num % i == 0)
13 isPrime = false;
14 i++;
15 }
16
17 if (isPrime)
18 System.out.println(num + " is a prime number");
19 else // !isPrime
20 System.out.println(num + " isn't a prime number");
21
22 }
23 }
As mentioned in the comments, dividing by 2 is a simplest optimization to reduce the number of checks, however, existing code has a few issues (eg returning true
for 0 and 1 which are NOT prime numbers) and may be further optimized:正如评论中提到的,除以 2 是减少检查次数的最简单优化,但是,现有代码存在一些问题(例如,对于不是素数的 0 和 1 返回true
)并且可以进一步优化:
isPrime
is set to false
一旦isPrime
设置为false
,就中断/结束循环i * i <= num
计算直到i * i <= num
i
of num
has been found in the range [2, num/i]
, therefore by definition of the prime numbers, all the remaining numbers in the range [num/i, num]
are neither the factors of num
, and therefore num
is prime.如果达到此限制,则意味着在[2, num/i]
范围内没有找到num
的因子i
,因此根据素数的定义,范围[num/i, num]
中的所有剩余数字都不是num
的因数,因此num
是素数。Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
boolean isPrime = num % 2 != 0 || num == 2;
int i = 3;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += 2; // skip even numbers
}
if (isPrime)
System.out.println(num + " is a prime number");
else
System.out.println(num + " isn't a prime number");
More optimizations are possible if the divisibles of 3 (except 3) are excluded similar to the exclusion of even numbers, then the search continues from 5 and the candidates for primality comply with 6n ± 1
rule (eg, 5 = 6 - 1, 7 = 6 + 1, 11 = 12 - 1, 13 = 12 + 1, etc.):如果排除 3 的整除数(除了 3)类似于排除偶数,则可能进行更多优化,然后从 5 继续搜索并且素数的候选符合6n ± 1
规则(例如,5 = 6 - 1, 7 = 6 + 1、11 = 12 - 1、13 = 12 + 1 等):
boolean isPrime = (num % 2 != 0 || num == 2) && (num % 3 != 0 || num == 3);
int i = 5;
int d = 2;
while (isPrime && i * i <= num) {
if (num % i == 0)
isPrime = false;
i += d; // check only non-even numbers
d = 6 - d; // switch 2 to 4 and back to 2
}
This is the simplest way to calculate if an integer n
is probably a prime:这是计算 integer n
是否可能是素数的最简单方法:
public static boolean isPrime (int n) {
if (n < 2) return false;
BigInteger bigInt = BigInteger.valueOf(n);
return bigInt.isProbablePrime(100);
}
You can insert this function call in a loop where you can pass a new number every iteration.您可以在循环中插入此 function 调用,您可以在每次迭代中传递一个新数字。 I am using the implementation of BigInteger
provided by Java to do the calculation, rather than writing my own.我使用 Java 提供的BigInteger
的实现来进行计算,而不是自己编写。 UNLESS this is a homework and you are required to write your own algorithm, I would use this solution.除非这是一项家庭作业并且您需要编写自己的算法,否则我会使用此解决方案。
This base method can then be used for calculating other types of prime numbers.然后,此基本方法可用于计算其他类型的素数。 A complete answer can be found here .完整的答案可以在这里找到。
UPDATE :更新:
The int
parameter in BigInteger.isProbablePrime(int)
is a measure of the uncertainty that the caller is willing to tolerate. BigInteger.isProbablePrime(int)
中的int
参数是调用者愿意容忍的不确定性的度量。 The larger the number, the "slower" it executes (but the more certain it is).数字越大,它执行的“越慢”(但越确定)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.