Signup/Sign In
LAST UPDATED: APRIL 4, 2022

C++ Program To Check Primeness Of An Array

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

A prime number is the one that 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 divide N. If yes then it is non-prime. Else it is prime.

Check Primeness Of An Array In C++

Approach:-

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

  • Function check prime(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 is prime tells if the 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 check prime( arr[i] ), if it results 1 ( isprime==1 ) then increment count.

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

#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;
}


Count of number of primes in array : 4

Conclusion

Here, in this tutorial, we have learned how to check the primeness of an array.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.