java判断素数的算法
时间: 2023-12-22 17:29:07 浏览: 93
以下是两种Java判断素数的算法:
1. 从2到x-1测试是否可以整除:
```java
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
boolean isPrime = true;
if (x == 1) {
isPrime = false;
}
for (int i = 2; i < x; i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(x + "是素数");
} else {
System.out.println(x + "不是素数");
}
}
}
```
2. 判断是否能被已知的且小于x的素数整除:
```java
public class PrimeNumber {
public static void main(String[] args) {
int[] primes = new int[50];
primes[0] = 2;
int cnt = 1;
Main: for (int x = 3; cnt < primes.length; x++) {
for (int i = 0; i < cnt; i++) {
if (x % primes[i] == 0) {
continue Main;
}
}
primes[cnt++] = x;
}
for (int k : primes) {
System.out.print(k + " ");
}
}
}
```
阅读全文