Count number of primes in an array in C++


We are given with an array of numbers. The goal is to find the count of prime numbers in that array.

A prime number is the one which is divisible by 1 and the number itself. It has only two factors. We will check if the number is prime starting from the first element till the last and increase the count of prime numbers found so far.

To check if the number N is prime, check if numbers between the range [2 to N/2], fully divides N. If yes then it is non-prime. Else it is prime.

Let’s understand with examples.

Input − arr[]= { 1,2,3,4,5,6,7,8,9 }

Output − Count of number of primes − 4

Explanation − Here 2,3,5,7 are primes and 1,4,6,8,9 are non-primes.

Input − arr[]= { 11,12,4,61,23 }

Output − Count of number of primes − 3

Explanation − Here 11,61,23 are primes and 12,4 are non-primes.

Approach used in the below program is as follows

  • We take an integer array arr[] containing random numbers.

  • Function checkPrime(int num) checks if the passed number num is prime or not. If it is prime, it returns 1 else it returns 0.

  • If the num is <=1 then it is non prime, return 0.

  • Now starting from 2 to num/2 if any number fully divides num ( num%i==0) then num is non-prime, return 0.

  • Else return 1.

  • Variable isprime tells if number is prime or not ( 1 means prime )

  • Variable count stores the number of primes in arr[]

  • Inside the main traverse whole array and pass each element arr[i] to checkPrime( arr[i] ), if it results 1 ( isprime==1 ) then increment count.

  • At the end count is the number of primes in arr[]

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
// Function to find if number is prime
int checkPrime(int num){
    if (num <= 1)
      { return 0; }
   // Check from 2 to half of arr[i]
   for (int j = 2; j <= num/2; j++){
      if (num % j == 0){
         return 0;
      }
      return 1;
   }
}
int main(){
   int arr[] = { 1,3,5,4,8,13,11 };
   int n = 7;
   int count=0;
   int isprime=0;
   for(int i=0;i<n;i++){
      isprime=checkPrime(arr[i]);
      if(isprime==1)
         count++;
   }
   cout<<"Count of number of primes in array : "<<count;
   return 0;
}

Output

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

Count of number of primes in array : 4

Updated on: 29-Aug-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements