VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-and-sum-of-composite-elements-in-an-array/

⇱ Count and Sum of composite elements in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count and Sum of composite elements in an array

Last Updated : 11 Jul, 2025

Given an array 'arr' of positive integers, the task is to count the number of composite numbers in the array. 

Note: 1 is neither Prime nor Composite.

Examples: 

Input: arr[] = {1, 3, 4, 5, 7} 
Output:
4 is the only composite number.

Input: arr[] = {1, 2, 3, 4, 5, 6, 7} 
Output:

Naive Approach: A simple solution is to traverse the array and do a primality test on every element.

Efficient Approach: Using Sieve of Eratosthenes generate a boolean vector upto the size of the maximum element from the array which can be used to check whether a number is prime or not. Also add 0 and 1 as a prime so that they don't get counted as composite numbers. Now traverse the array and find the count of those elements which are composite using the generated boolean vector.

Below is the implementation of the above approach: 


Output
Count of Composite Numbers = 2
Sum of Composite Numbers = 10

Complexity Analysis:

  • Time complexity : O(n log(log n))
  • Space complexity: O(n) since auxiliary space is being used
Comment