Java 程序检查数字是否为素数
给定一个数字,假设为 N,编写一个 Java 程序来检查给定的数字是否为素数。素数是只有两个因数 1 和它本身的特殊数字,它们不能被任何其他数字整除。
示例场景 1
Input: num = 1; Output: 1 is not a prime number
示例场景 2
Input: num2 = 5; Output: 5 is a prime number
5 只能被 1 和 5 整除
使用因式分解检查素数
检查给定数字是否为素数的朴素方法是 因式分解。在这个过程中,我们首先将给定数字除以所有小于或等于它的自然数,然后检查因数的数量。如果因数的数量只有两个,则给定数字是素数,否则不是。
示例
以下示例是上述方法的实际说明。
public class Example {
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 程序说明了如何以更优化的方式检查给定数字是否为素数。
public class Example {
public static boolean checkPrimeFunc(int nums) {
if (nums <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(nums); i++) {
if (nums % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int num = 29;
System.out.println("The given number is: " + num);
System.out.println(num + " is prime ? " + checkPrimeFunc(num));
}
}
执行上述代码后,将显示以下结果 -
The given number is: 29 29 is prime ? true
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP