w3resource
Java Programming Exercies

Java Exercises: Print the number of prime numbers which are less than or equal to a given integer

Java Basic: Exercise-217 with Solution

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).

Pictorial Presentation:

Java Basic Exercises: Print the number of prime numbers which are less than or equal to a given integer.

Sample Solution:

Java Code:

 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

Flowchart:

Flowchart: Java exercises: Print the number of prime numbers which are less than or equal to a given integer.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program which reads an integer n and find the number of combinations of a,b,c and d (0 ≤ a,b,c,d ≤ 9) where (a + b + c + d) will be equal to n.
Next: Write a Java program to compute the radius and the central coordinate (x, y) of a circle which is constructed by three given points on the plane surface.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming