Q:

Write a Java program to print the number of prime numbers which are less than or equal to a given integer

0

 Write a Java program to print the number of prime numbers which are less than or equal to a given integer

Input:

n (1 ≤ n ≤ 999,999)

Expected Output:

Input the number(n):
 1235
Number of prime numbers which are less than or equal to n.:
202

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

 import java.util.Scanner;
public class Main {
 
    public static void main(String[] args) {
        System.out.println("Input the number(n):");
		Scanner s = new Scanner(System.in);
            int c = s.nextInt();
            int ans = check(c);
			System.out.println("Number of prime numbers which are less than or equal to n.:");
            System.out.println(ans);
       }
    static int check(int c) {
        boolean[] prime = new boolean[c+1];
        int count = 0;
        for(int i = 2; i <= Math.sqrt(c); i++) {
            for(int j = i + i; j <= c; j += i) {
                prime[j] = true;
            }
        }
        for(int i = 2; i <= c; i++) {
            if(!prime[i]) {
                count++;
            }
        }
        return count;
    }
}

Sample Output:

Input the number(n):
 1235
Number of prime numbers which are less than or equal to n.:
202

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now