Java实现 输入一个数,判断其是否素数。素数是大于1的自然数中,除了1和它本身以外不再有其他因数
时间: 2023-05-27 18:06:06 浏览: 68
的数。
```
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个数:");
int num = scanner.nextInt();
if (isPrime(num)) {
System.out.println(num + "是素数");
} else {
System.out.println(num + "不是素数");
}
}
public static boolean isPrime(int num) {
if (num <= 1) { // 小于等于1的数不是素数
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) { // 可以被整除,不是素数
return false;
}
}
return true;
}
}
```
相关问题
输入一个数,判断其是否素数。素数是大于1的自然数中,除了1和它本身以外不再有其他因数
。答案:
以下是Python代码实现:
```python
num = int(input("请输入一个数:"))
if num <= 1:
print("不是素数")
else:
for i in range(2, num):
if num % i == 0:
print("不是素数")
break
else:
print("是素数")
```
首先输入一个数,然后判断它是否小于等于1,如果是则不是素数。
如果不是,则从2开始循环到这个数的前一个数,判断这个数是否是这个数的因数。如果存在因数,则说明不是素数,输出“不是素数”并退出循环。如果不存在因数,则说明是素数,输出“是素数”。
python程序 输入一个数,判断其是否素数。素数是大于1的自然数中,除了1和它本身以外不再有其他因数
好的,我可以为您编写一个Python程序来判断一个数是否为素数。以下是程序代码:
```python
num = int(input("请输入一个自然数:"))
# 判断num是否为素数
if num > 1:
# 找出num的因数
factors = [i for i in range(2, num) if num % i == 0]
if len(factors) == 0:
print(num, "是素数")
else:
print(num, "不是素数")
else:
print(num, "不是素数")
```
程序先让用户输入一个自然数,然后通过判断该数是否大于1来确定它是否为素数。如果大于1,则找出该数的所有因数,如果因数的个数为0则说明该数是素数,否则说明该数不是素数。如果输入的数不大于1,则直接输出该数不是素数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)