方法一:
方法一:
class PrimeNum {
public static void main(String[] args) {
//定义变量b,控制换行,计算质数个数
int b = 0;
for (int i = 2; i <= 100; i++) {
int a = 2;
//判断是否为质数
for (int n = 2; n < i; n++) {
//不能整除时,a与i增加量相同
if ((i % n) != 0) {
a++;
}
}
if (a == i) {
b++;
//输出质数
System.out.print(i + "\t");
//每输出10个质数,利用b,进行换行
if ((b % 10) == 0) {
System.out.println();
}
}
}
System.out.println("\n共有" + b + "个质数");
}
}
方法二:
class Primer {
public static void main(String[] args) {
int b = 0;
for (int i = 2; i <= 100; i++) {
int n;
for (n = 2; n < Math.sqrt(i); n++) {
if (i % n == 0) {
break;
}
}
if (n > Math.sqrt(i)) {
System.out.print(i + "\t");
//利用b,每输出十个数换行
b++;
if (b % 10 == 0) {
System.out.println();
}
}
}
}
}
class Primer1 {
public static void main(String[] args) {
int b = 0;
outer:
for (int i = 2; i <= 100; i++) {
int n;
for (n = 2; n < Math.sqrt(i); n++) {
if (i % n == 0) {
continue outer;
}
}
if (n > Math.sqrt(i)) {
System.out.print(i + "\t");
//利用b,每输出十个数换行
b++;
if (b % 10 == 0) {
System.out.println();
}
}
}
}
}