Given an integer k and an array of integers arr, the task is to find the sum and product of k smallest and k largest composite numbers in the array.
Assume that there are at least k composite numbers in the array.
Examples:
Input: arr[] = {2, 5, 6, 8, 10, 11}, k = 2
Output: Sum of k-minimum composite numbers is 14
Sum of k-maximum composite numbers is 18
Product of k-minimum composite numbers is 48
Product of k-maximum composite numbers is 80
{6, 8, 10} are the only comsposite numbers from the array. {6, 8} are the 2 smallest and {8, 10} are the 2 largest among them.Input: arr[] = {6, 4, 2, 12, 13, 5, 19, 10}, k = 3
Output: Sum of k-minimum composite numbers is 20
Sum of k-maximum composite numbers is 28
Product of k-minimum composite numbers is 240
Product of k-maximum composite numbers is 720
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 composite or not.
- Also set 0 and 1 as prime so that they don’t get counted as composite numbers.
- Now traverse the array and insert all the numbers which are composite in two heaps, a min heap and a max heap.
- Now, pop out top k elements from the min heap and take the sum and product of the minimum k composite numbers.
- Do the same with the max heap to get the sum and product of the max k composite numbers.
- Finally, print the results.
Below is the implementation of the above approach:
// C++ program to find the sum and // product of k smallest and k largest // composite numbers in an array #include <bits/stdc++.h> using namespace std;
vector< bool > SieveOfEratosthenes( int max_val)
{ // Create a boolean vector "prime[0..n]". A
// value in prime[i] will finally be false
// if i is Not a prime, else true.
vector< bool > prime(max_val + 1, true );
for ( int p = 2; p * p <= max_val; p++) {
// If prime[p] is not changed, then
// it is a prime
if (prime[p] == true ) {
// Update all multiples of p
for ( int i = p * 2; i <= max_val; i += p)
prime[i] = false ;
}
}
return prime;
} // Function that calculates the sum // and product of k smallest and k // largest composite numbers in an array void compositeSumAndProduct( int arr[], int n, int k)
{ // Find maximum value in the array
int max_val = *max_element(arr, arr + n);
// Use sieve to find all prime numbers
// less than or equal to max_val
vector< bool > prime = SieveOfEratosthenes(max_val);
// Set 0 and 1 as primes so that
// they don't get counted as
// composite numbers
prime[0] = true ;
prime[1] = true ;
// Max Heap to store all the composite numbers
priority_queue< int > maxHeap;
// Min Heap to store all the composite numbers
priority_queue< int , vector< int >, greater< int >>
minHeap;
// Push all the composite numbers
// from the array to the heaps
for ( int i = 0; i < n; i++)
if (!prime[arr[i]]) {
minHeap.push(arr[i]);
maxHeap.push(arr[i]);
}
long long int minProduct = 1
, maxProduct = 1
, minSum = 0
, maxSum = 0;
while (k--) {
// Calculate the products
minProduct *= minHeap.top();
maxProduct *= maxHeap.top();
// Calculate the sum
minSum += minHeap.top();
maxSum += maxHeap.top();
// Pop the current minimum element
minHeap.pop();
// Pop the current maximum element
maxHeap.pop();
}
cout << "Sum of k-minimum composite numbers is " << minSum << "\n" ;
cout << "Sum of k-maximum composite numbers is " << maxSum << "\n" ;
cout << "Product of k-minimum composite numbers is " << minProduct << "\n" ;
cout << "Product of k-maximum composite numbers is " << maxProduct;
} // Driver code int main()
{ int arr[] = { 4, 2, 12, 13, 5, 19 };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 3;
compositeSumAndProduct(arr, n, k);
return 0;
} |
// Java program to find the sum and // product of k smallest and k largest // composite numbers in an array import java.util.*;
class GFG
{ static boolean [] SieveOfEratosThenes( int max_val)
{
// Create a boolean vector "prime[0..n]". A
// value in prime[i] will finally be false
// if i is Not a prime, else true.
boolean [] prime = new boolean [max_val + 1 ];
Arrays.fill(prime, true );
for ( int p = 2 ; p * p <= max_val; p++)
{
// If prime[p] is not changed, then
// it is a prime
if (prime[p])
{
// Update all multiples of p
for ( int i = p * 2 ; i <= max_val; i += p)
prime[i] = false ;
}
}
return prime;
}
// Function that calculates the sum
// and product of k smallest and k
// largest composite numbers in an array
static void compositeSumAndProduct(Integer[] arr,
int n, int k)
{
// Find maximum value in the array
int max_val = Collections.max(Arrays.asList(arr));
// Use sieve to find all prime numbers
// less than or equal to max_val
boolean [] prime = SieveOfEratosThenes(max_val);
// Set 0 and 1 as primes so that
// they don't get counted as
// composite numbers
prime[ 0 ] = true ;
prime[ 1 ] = true ;
// Max Heap to store all the composite numbers
PriorityQueue<Integer> maxHeap =
new PriorityQueue<Integer>((x, y) -> y - x);
// Min Heap to store all the composite numbers
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Push all the composite numbers
// from the array to the heaps
for ( int i = 0 ; i < n; i++)
{
if (!prime[arr[i]])
{
minHeap.add(arr[i]);
maxHeap.add(arr[i]);
}
}
long minProduct = 1 , maxProduct = 1 ,
minSum = 0 , maxSum = 0 ;
Integer lastMin = 0 , lastMax = 0 ;
while (k-- > 0 )
{
if (minHeap.peek() != null ||
maxHeap.peek() != null )
{
// Calculate the products
minProduct *= minHeap.peek();
maxProduct *= maxHeap.peek();
// Calculate the sum
minSum += minHeap.peek();
maxSum += maxHeap.peek();
// Pop the current minimum element
lastMin = minHeap.poll();
// Pop the current maximum element
lastMax = maxHeap.poll();
}
else {
// when maxHeap or minHeap is exhausted
// then this consition will run
minProduct *= lastMin;
maxProduct *= lastMax;
minSum += lastMin;
maxSum += lastMax;
}
}
System.out.println( "Sum of k-minimum composite" +
" numbers is " + minSum);
System.out.println( "Sum of k-maximum composite" +
" numbers is " + maxSum);
System.out.println( "Product of k-minimum composite" +
" numbers is " + minProduct);
System.out.println( "Product of k-maximum composite" +
" numbers is " + maxProduct);
}
// Driver Code
public static void main(String[] args)
{
Integer[] arr = { 4 , 2 , 12 , 13 , 5 , 19 };
int n = arr.length;
int k = 3 ;
compositeSumAndProduct(arr, n, k);
}
} // This code is contributed by // sanjeev2552 |
Sum of k-minimum composite numbers is 28 Sum of k-maximum composite numbers is 20 Product of k-minimum composite numbers is 576 Product of k-maximum composite numbers is 192
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.