使用java的while语句写出一个判断质数的代码
时间: 2023-05-17 17:05:43 浏览: 112
以下是使用 Java 的 while 语句写出判断质数的代码:
```
import java.util.Scanner;
public class PrimeNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个正整数:");
int number = scanner.nextInt();
boolean isPrime = true;
int i = 2;
while (i <= number / 2) {
if (number % i == 0) {
isPrime = false;
break;
}
i++;
}
if (isPrime) {
System.out.println(number + " 是质数");
} else {
System.out.println(number + " 不是质数");
}
}
}
```
该程序会提示用户输入一个正整数,然后使用 while 循环从 2 开始逐个判断该数是否能被 2 到该数的一半之间的任意一个数整除,如果能整除,则该数不是质数,否则该数是质数。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![text/plain](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)