Take Input From User And Count How Many Prime Numbers Come Before That Number | Java Programs

Output:

*** How Many Prime Numbers Are There Before Entered Number ***

Enter a number: 8
Before 8 there are 4 prime numbers.

Click Here For Java Online Compiler

Solution:

import java.util.*;

public class HowManyPrimes {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("*** How Many Prime Numbers Before Entered Number ***");
        System.out.println();
        System.out.print("Enter a number: ");
        int x = scanner.nextInt();
        System.out.print("Before " + x + " there are " + countPrimes(x) + " prime numbers.");
        System.out.println();
    }

    static int countPrimes(int n) {
        if (n <= 0 || n == 1 || n == 2) {
            return 0;
        } else if (n == 3) {
            return 1;
        }
        BitSet set = new BitSet();
        n = n - 1;
        int s = (int) Math.sqrt(n);
        int ctr = n;
        for (int p = 2; p <= s; p++) {
            if (!set.get(p)) {
                for (int q = 2; (p * q) <= n; q++) {
                    if (!set.get(p * q)) {
                        ctr--;
                        set.set(p * q);
                    }
                }
            }
        }
        return ctr - 1;
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon