2. 求100以内的素数,要求在控制台显示出来。给出代码并注释
时间: 2024-10-23 17:18:39 浏览: 31
在Java中,我们可以编写一个简单的程序来找出100以内的所有素数。素数是指只有两个正因数(1和自身)的大于1的整数。下面是一段示例代码及其注释:
```java
public class PrimeNumbers {
public static void main(String[] args) {
// 定义一个范围,这里是1到100
int limit = 100;
// 遍历从2到limit,假设每个数都是素数
for (int num = 2; num < limit; num++) {
boolean isPrime = true;
// 检查num是否能被从2到num-1之间的任何数整除
for (int divisor = 2; divisor < num; divisor++) {
if (num % divisor == 0) { // 如果可以整除,则num不是素数
isPrime = false;
break;
}
}
// 如果isPrime仍然为true,说明num是素数,打印它
if (isPrime) {
System.out.print(num + " ");
}
}
}
}
```
在这段代码中,
1. 我们首先设置了一个上限(100),然后遍历这个范围内的所有数;
2. 对于每个数(num),我们检查它是否能被小于它的数整除,如果找到因子就不再是素数,标记`isPrime`为`false`;
3. 如果`isPrime`依然为`true`,则表示num是素数,将其打印出来。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)