Answer to Question #289061 in Java | JSP | JSF for HEHE

Question #289061

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


1
Expert's answer
2022-01-20T09:47:18-0500
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();
            }
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog