大家!我有一个 java 应用程序,它显示从 2 到给定数字(用户输入)的所有素数。我怎样才能打印出给定范围内的最后一个数字,我的意思是最大的一个?例如:如果用户输入的是 12,编译器只打印 11,而不是 2,3,5,7,11。这是代码:
package sieve_eratos;
import java.util.Scanner;
public class Sieve_Eratos {
public static void main(String[] args) {
// get the ceiling on our prime numbers
int N;
Scanner sc = new Scanner(System.in);
System.out.print("enter the prime number ceiling: ");
N = sc.nextInt();
sc.close();
int k = 0;
// init numbers array, where true denotes primality
boolean[] isPrime = new boolean[N];
// init possible primes
isPrime[0] = false; // 1 is not prime
for (int i = 1; i < N; i++) {
isPrime[i] = true;
k = k + 1;
}
// check every number >= 2 for primality
for (int i = 2; i <= N; i++) {
// i is prime if it hasn't been "crossed off" yet
if (isPrime[i - 1]) {
// print out the prime number
System.out.println(i);
// "cross off" all the subsequent multiples of i
//for (int j = 2*i; j <= N; j += i) {
for (int j = i * i; j <= N; j += i) { // more efficient
isPrime[j - 1] = false;
}
}
}
}
}
我正在考虑创建另一个整数数组,然后调用最后一个元素(这将是存储的最后一个数字),但我不知道该怎么做。先感谢您!