Saturday, December 7, 2013

Java Program to count prime numbers below a given number.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class PrimeNumbers {

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));
        System.out.println(" Enter the limit for the prime number ");
        int limit = Integer.parseInt(reader.readLine());
        int count = 0,total_count=0;
       
        for (int index1 = 1; index1 < limit; index1++) {
            for (int index2 = 1; index2 <= index1; index2++) {
                if (index1 % index2 == 0) {
                    count++;
                }
            }
            if (count == 2) {
                System.out.print(index1 + "\t");
                total_count++;

            }
            count = 0;
        }

        System.out.println();
        System.out.println(" Total Number of prime numbers = "+total_count);
    }

}

No comments:

Post a Comment