Separating Composite and Prime Numbers in Java

Write a program to input any n numbers in a single dimensional array arr[], now store all the prime numbers in the array prim[] and all the composite numbers in the array com[]. Display the contents of both the arrays prim[] and com[].

Program:

import java.io.*;
class Arrange{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Number of elements: ");
        int n = Integer.parseInt(br.readLine());
        int arr[] = new int[n];
        int i = 0;
        int j = 0;
        int k = 0;
        int countc = 0;
        int countp = 0;
        for(i = 0; i < arr.length; i++){
            System.out.print("Enter element: ");
            arr[i] = Integer.parseInt(br.readLine());
            if(isPrime(arr[i]))
                countp++;
            else
                countc++;
        }
        int prim[] = new int[countp];
        int com[] = new int[countc];
        for(i = 0; i < arr.length; i++){
            if(isPrime(arr[i]))
                prim[j++] = arr[i];
            else
                com[k++] = arr[i];
        }
        System.out.println("Prime Numbers:");
        for(i = 0; i < prim.length; i++)
            System.out.print(prim[i] + "\t");
        System.out.println("\nComposite Numbers:");
        for(i = 0; i < com.length; i++)
            System.out.print(com[i] + "\t");
    }
    public static boolean isPrime(int n){
        int f = 0;
        for(int i = 1; i <= n; i++)
            if(n % i == 0)
                f++;
        if(f == 2)
            return true;
        return false;
    }
}

4 thoughts on “Separating Composite and Prime Numbers in Java”

  1. Sir,in the above program,the output is showing like this:
    Number of elements: 10
    Enter element: 1
    Enter element: 2
    Enter element: 3
    Enter element: 4
    Enter element: 5
    Enter element: 6
    Enter element: 7
    Enter element: 8
    Enter element: 9
    Enter element: 10
    Prime Numbers:
    2 3 5 7
    Composite Numbers:
    1 4 6 8 9 10
    As you have told 1 is neither prime nor composite but 1 is being displayed in the composite array.Sir,can you please explain why is it so?

  2. Sir,In the above program if we accept 1 as element of the array,in which array will it display prime or composite?

Leave a Reply

%d bloggers like this: