Java 检查一个数字是不是质数
质数是特殊的数字,它只有两个因子1和该数字本身,它们不能被任何其他数字整除。因此,要检查给定的数字是否是质数,首先我们将给定的数字除以小于或等于它的所有自然数,然后我们检查因子的数量。如果因子的数量只有两个,那么这个给定的数字是质数,否则不是。这种检查质数的方法称为分解因子。现在,让我们通过实现上述逻辑来了解如何判断一个给定的数字是不是质数。
Java程序检查一个数字是不是质数
在进入检查质数的示例程序之前,让我们通过一个实例来正确解释问题陈述。
实例
输入1
1
输出
1 is not a prime number
输入2
5
输出
5 is a prime number
示例1
下面的示例说明了如何从用户那里接收一个数字作为输入,并检查该数是否为质数。
方法
- 首先,定义一个计数变量,用于存储给定数字的因子数量。
-
然后,创建一个 Scanner 类的实例,以便我们可以从用户那里接收输入。
-
接下来,采用 if-else 块来检查输入是否为质数。如果输入为 2,则打印它是质数,否则转到 else 块中,我们将使用 for 循环来检查因子的数量。
-
现在,采用另一个 if-else 块来检查因子的数量。如果是 2,则打印质数,否则不是质数。
import java.util.*;
public class Example1 {
public static void main(String[] args) {
// initial count of factors
int count = 0;
// creating an instance of Scanner class
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number to check prime number");
// to take input from user
int num = sc.nextInt();
// to check prime number
if(num == 2) {
System.out.println(num + " is a prime number");
} else {
// checking number of factors
for(int i = 1; i <= num; i++) {
if(num % i == 0) {
count++;
}
}
// checking number of counts to print result
if(count == 2) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}
}
}
}
输出1
Enter a number to check prime number
13
13 is a prime number
输出2
Enter a number to check prime number
56
56 is not a prime number
示例2
在这个Java程序中,我们将不再从用户那里获取输入,而是将一个整数变量初始化为检查它是否为质数。我们不会改变程序的逻辑。
public class Example2 {
public static void main(String[] args) {
int num = 89;
System.out.println("The given number is: " + num);
// initial count of factors
int count = 0;
// to check prime number
if(num == 2) {
System.out.println(num + " is a prime number");
} else {
// checking number of factors
for(int i = 1; i <= num; i++) {
if(num % i == 0) {
count++;
}
}
// checking number of counts to print result
if(count == 2) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}
}
}
}
输出
The given number is: 89
89 is a prime number
结论
本文首先解释了什么是素数的条件,以及如何检查给定的数字是否为素数。然后,我们编写了两个不同的Java程序,使用if-else语句和for循环来识别素数。