Count Primes in Ranges in C++

C++Server Side ProgrammingProgramming

We are given range variables START and END. The goal is to find the count of prime numbers in the range [START,END].

We will check if number i in range is prime by checking if any number other than 1 fully divides it and is between 1 and i/2. If it is prime. Increment count.

Let’s understand with examples.

Input 

Start=1 End=20

Output 

Primes in Ranges : 8

Explanation 

Primes between 1 and 20 are: 2,3,5,7,11,13,17,19.

Input 

Start=100 End=200

Output 

Primes in Ranges : 21

Explanation 

Primes between 100 and 200 are: 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199

Approach used in the below program is as follows

  • We take range variables as START and END.

  • Function countPrimes(int strt,int end) returns the count of primes in range.

  • Take the initial variable count as 0.

  • Traverse using for loop from i=strt to i <=end

  • Take each number i and check if it is prime using isprime(i).

  • Function isprime(int num) returns 0 if the number is non prime and 1 if it is prime.

  • After the end of loop, return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int isprime(int num){
   if (num <= 1)
      return 0;
   for (int i = 2; i <= num/2; i++){
      if (num % i == 0)
         { return 0; }
   }
   return 1; //if both failed then num is prime
}
int countPrimes(int strt,int end){
   int count=0;
   for(int i=strt;i<=end;i++){
      if(isprime(i)==1)
         { count++; }
   }
   return count;
}
int main(){
   int START=10, END=20;
   cout <<endl<<"Primes in Ranges : "<<countPrimes(START,END);
   return 0;
}

Output

If we run the above code it will generate the following output −

Primes in Ranges : 4
raja
Published on 31-Oct-2020 05:20:24
Advertisements