1.判断任意一个数是不是质数
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean b = true;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
b = false;
}
}
if (b) {
System.out.println("是质数");
} else {
System.out.println("不是质数");
}
}
}
2.输出100-200以内的质数及个数
public class Main2 {
public static void main(String[] args) {
int sum = 0;
for (int i = 100; i < 200; i++) {
boolean b = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
b = false;
}
}
if (b) {
System.out.println(i);
sum++;
}
}
System.out.println("质数个数: " + sum);
}
}
答案:101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
质数个数: 21