以下提供两种解法个思路
/*
* 求1-100中质数的和
*
* 2 3 5 7 11 13 17 19 23 29 31
*
*
*/
public class Demo2 {
public static void main(String[] args) {
method1();
method2();
// 理解
method3();
}
private static void method3() {
int count = 0;
for (int x = 2; x <= 100; x++) {
int y = 2;
while (x % y != 0) {
y++;
}
if (x == y) {
System.out.println(x);
count++;
}
}
System.out.println("1-100中的质数的个数是:" + count);
}
private static void method2() {
int count = 0;
for (int x = 2; x <= 100; x++) {
int count1 = 0;
for (int y = 2; y <= x; y++) {
if (x % y == 0) {
count1++;
}
}
if (count1 > 1) {
System.out.println(x);
count++;
}
}
System.out.println("1-100中的合数的个数是:" + count);
}
private static void method1() {
// 1不是素数,所以直接从2开始循环
int count = 0;
for (int x = 2; x <= 100; x++) {
int count1 = 0;
for (int y = 2; y <= x; y++) {
if (x % y == 0) {
count1++;
}
}
if (count1 == 1) {
System.out.println(x);
count++;
}
}
System.out.println("1-100中的质数的个数是:" + count);
}
}
|