题目要求输入一个正整数N,筛选出N以内的素数。
解析:先搞清楚素数是什么,素数也称为质素,是在所有大于1的自然数中,只有1和这个数本身两个因数的数,例如:1、3、5、7等。所以对素数的判断条件可以通过N%i==0(2<i<N)来进行判断。
package _12_26_test;
import java.util.Scanner;
public class TestThree {
public static void main(String[] args) {
System.out.println("输入一个整数:");
Scanner scanner = new Scanner(System.in);
int get = scanner.nextInt();
for (int i = 2; i < get; i++) {
// 如果这个数是2,则直接进行输出
if (i == 2) {
System.out.println(i);
}
if (judge(i) && i != 2) {
System.out.println(i);
}
}
}
public static boolean judge(int Num) {
// 循环一遍所有大于1,小于N的数,如果N能够整除以其中的某个数,则这个N就不是素数
for (int i = 2; i < Num; i++) {
if (Num % i == 0) {
return false;
}
}
return true;
}
}
测试效果: