# Count the prime numbers in a certain range in Java

Hey folks, today we will see how to count the prime numbers in a certain range in Java.

For this purpose, we won’t be using any predefined methods and will code the logic from scratch.

So, let’s look at the problem statement and make our goal clear. Basically there we will be two variables say r1 and r2 and our task is to find the prime numbers in that range.

What we would be doing is iterating over the given range and checking each element for prime, if it is prime then we will increment the count.

But we will try to make our program efficient, for this, we will check for factors in the range 2 to number/2, this will reduce iterations to half.

So let’s go straight to our code.

class test { int checkPrime(int n) { for(int i=2;i<n/2;i++) { if(n%i==0) { return 0; } } return 1; } } public class primeRange { public static void main(String []args) { test t1=new test(); int starting=10; int ending=20; int cnt=0; for (int i=starting;i<=ending;i++) { if(t1.checkPrime(i)==1) { cnt++; } } System.out.println("NUmber of prime numbers in the given range is: "+cnt); } }

In the above code, we are finding the number of prime numbers in range 10 to 20.

In the above program, we have used the Object-Oriented programming concepts, as you can see we have made two classes :

- Test
- primeRange

The Test class contains a function “checkPrime()” which checks a certain for prime and returns 1 if it prime otherwise returns 0.

The primeRange class contains the main method and contains the logic for counting prime numbers in a certain range.

### Our Logic for Finding Prime Number

We have used the logic a prime number does not contain any factor between 2 and number/2.If we find a factor in this range that means the number is not prime rather it is composite. By implementing this logic we reduce the iterations required as compared to the traditional way of finding prime numbers.

Thanks for stopping by.

Have a nice day ahead, and do let me know if you have any queries in the comments down below.

Also, read: Java program to find maximum and minimum element in an Array

For efficiency use square root of n not n/2

Also calculate the search limit before search loop to.prevent it being calculated every iteration of the loop