1. Introduction
An integer greater than 1, if its positive factor is only 1 and itself, then the integer is a prime number.
For example: 2, 3, 5, and 7 are all prime numbers, but 4, 6, 8, 9 are not
2. Code
package com.zhuo.base.com.zhuo.base;
public class PrimeNumber {
public static void main(String[] args) {
final int NUMBER_OF_PRIME = 50;//要显示的素数
final int NUMBER_OF_PRIME_PER_LINE = 10;//每行显示10个
int count = 0;//统计素数的个数
int number = 2;//要测试是不是素数的数
System.out.println("The first 50 prime numbers are \n");
//反复寻找素数
while (count < NUMBER_OF_PRIME) {
boolean isPrime = true;// //是素数的标记,初始化为素数
for (int divisor = 2;divisor <= number / 2;divisor ++) {
if (number % divisor == 0) {
isPrime = false;//不是素数置为假
break;//跳出循环
}
}
//标记为真,说明是素数
if (isPrime) {
count++;//素数个数加一
//每行输出十个素数
if (count % NUMBER_OF_PRIME_PER_LINE == 0) {
System.out.println(number);
}
else
System.out.print(number + " ");
}
number++;
}
}
}
Three. Results display
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
Process finished with exit code 0