Answer to Question #196548 in Java | JSP | JSF for harsha

Question #196548

Rohan was asked by his teacher to develop a program which takes in a dynamic user input and prints all the prime numbers till that number and then prints all the composite numbers till that number. Help him out by developing the program to do so


1
Expert's answer
2021-05-21T06:49:32-0400
import java.util.Scanner;

public class Main {
    private static final boolean[] numbers = new boolean[Integer.MAX_VALUE / 2];

    private static void markNumbers() {
        for (int i = 2; i * i < numbers.length; i++) {
            if (!numbers[i]) {
                for (int j = i * i; j < numbers.length; j += i) {
                    numbers[j] = true;
                }
            }
        }
    }

    private static void showNumbers(int n) {
        System.out.print("Primes:");
        for (int i = 2; i <= n; i++) {
            if (!numbers[i]) {
                System.out.print(" " + i);
            }
        }
        System.out.println();
        System.out.print("Composites:");
        for (int i = 2; i <= n; i++) {
            if (numbers[i]) {
                System.out.print(" " + i);
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        markNumbers();
        Scanner in = new Scanner(System.in);
        int n;
        do {
            System.out.print("Enter the number(0 to stop): ");
            n = in.nextInt();
            if (n > 1 && n < numbers.length) {
                showNumbers(n);
            }
        }while (n != 0);
    }
}

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
APPROVED BY CLIENTS