Write a program to implement Eratosthenes Sieve. The program should ask the user for an upper bound and should then print all the prime numbers less than or equal to that upper bound. In your program, use a boolean array to maintain a record of the numbers that are possible primes.
The output should have eight values per line with each value right-justified in a field that is ten characters wide. You may find the methods of the Out class shown in Appendix A useful for this.
Number 1which can be found on http://ntci.on.ca/compsci/java/ch8/8_7.html
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Upper bound:");
int upperBound = in.nextInt();
boolean[] primes = new boolean[upperBound + 1];
for (int i = 2; i < primes.length; i++) {
for (int j = i * i; j < primes.length; j += i) {
primes[j] = true;
}
}
int counter = 0;
for (int i = 2; i < primes.length; i++) {
if (!primes[i]) {
System.out.printf("%10d", i);
counter++;
}
if (counter == 8) {
counter = 0;
System.out.println();
}
}
}
}
Comments
Leave a comment