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


Expert's answer

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!

LATEST TUTORIALS
APPROVED BY CLIENTS