Product of every K’th prime number in an array

Given an integer ‘k’ and an array of integers ‘arr’ (less than 10^6), the task is to find the product of every K’th prime number in the array.

Examples: 

Input: arr = {2, 3, 5, 7, 11}, k = 2 
Output: 21 
All the elements of the array are prime. So, the prime numbers after every K (i.e. 2) interval are 3, 7 and their product is 21. 

Input: arr = {41, 23, 12, 17, 18, 19}, k = 2 
Output: 437 

A simple approach: Traverse the array and find every K’th prime number in the array and calculate the running product. In this way, we’ll have to check every element of the array whether it is prime or not which will take more time as the size of the array increases.

C++
#include <cmath>
#include <iostream>
#include <vector>

using namespace std;

// Function to check if a number is prime
bool is_prime(int num)
{
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i <= sqrt(num); ++i) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

// Function to find the product of every K'th prime number
// in the array
int product_of_kth_primes(const vector<int>& arr, int k)
{
    int product = 1;
    int prime_count = 0;

    // Iterate through each number in the array
    for (int num : arr) {
        // Check if the number is prime
        if (is_prime(num)) {
            // Increment the count of prime numbers found
            prime_count++;
            // If the count is a multiple of K, multiply the
            // product by the prime number
            if (prime_count % k == 0) {
                product *= num;
            }
        }
    }
    // Return the final product
    return product;
}

int main()
{
    vector<int> arr1 = { 2, 3, 5, 7, 11 };
    int k1 = 2;
    // Output: 21
    cout << "Product of kth primes: "
         << product_of_kth_primes(arr1, k1) << endl;

    vector<int> arr2 = { 41, 23, 12, 17, 18, 19 };
    int k2 = 2;
    // Output: 437
    cout << "Product of kth primes: "
         << product_of_kth_primes(arr2, k2) << endl;

    return 0;
}
Java
import java.util.ArrayList;

public class Main {
    public static boolean isPrime(int num)
    {
        // Function to check if a number is prime
        if (num <= 1) {
            return false;
        }
        // Iterate through possible divisors up to the
        // square root of the number
        for (int i = 2; i <= Math.sqrt(num); i++) {
            // If the number is divisible by any other
            // number, it's not prime
            if (num % i == 0) {
                return false;
            }
        }
        // If no divisors are found, the number is prime
        return true;
    }

    public static int productOfKthPrimes(int[] arr, int k)
    {
        // Function to find the product of every K'th prime
        // number in the array
        int product = 1;
        int primeCount = 0;
        // Iterate through each number in the array
        for (int num : arr) {
            // Check if the number is prime
            if (isPrime(num)) {
                // Increment the count of prime numbers
                // found
                primeCount++;
                // If the count is a multiple of K, multiply
                // the product by the prime number
                if (primeCount % k == 0) {
                    product *= num;
                }
            }
        }
        // Return the final product
        return product;
    }

    public static void main(String[] args)
    {
        int[] arr1 = { 2, 3, 5, 7, 11 };
        int k1 = 2;
        // Output: 21
        System.out.println(productOfKthPrimes(arr1, k1));

        int[] arr2 = { 41, 23, 12, 17, 18, 19 };
        int k2 = 2;
        // Output: 437
        System.out.println(productOfKthPrimes(arr2, k2));
    }
}
Python
def is_prime(num):
    # Function to check if a number is prime
    if num <= 1:
        return False
    # Iterate through possible divisors up to the square root of the number
    for i in range(2, int(num ** 0.5) + 1):
        # If the number is divisible by any other number, it's not prime
        if num % i == 0:
            return False
    # If no divisors are found, the number is prime
    return True


def product_of_kth_primes(arr, k):
    # Function to find the product of every K'th prime number in the array
    product = 1
    prime_count = 0
    # Iterate through each number in the array
    for num in arr:
        # Check if the number is prime
        if is_prime(num):
            # Increment the count of prime numbers found
            prime_count += 1
            # If the count is a multiple of K, multiply the product by the prime number
            if prime_count % k == 0:
                product *= num
    # Return the final product
    return product


# Example usage
arr1 = [2, 3, 5, 7, 11]
k1 = 2
# Output: 21
print(product_of_kth_primes(arr1, k1))

arr2 = [41, 23, 12, 17, 18, 19]
k2 = 2
# Output: 437
print(product_of_kth_primes(arr2, k2))
JavaScript
function isPrime(num) {
    // Function to check if a number is prime
    if (num <= 1) {
        return false;
    }
    // Iterate through possible divisors up to the square root of the number
    for (let i = 2; i <= Math.sqrt(num); i++) {
        // If the number is divisible by any other number, it's not prime
        if (num % i === 0) {
            return false;
        }
    }
    // If no divisors are found, the number is prime
    return true;
}

function productOfKthPrimes(arr, k) {
    // Function to find the product of every K'th prime number in the array
    let product = 1;
    let primeCount = 0;
    // Iterate through each number in the array
    for (let num of arr) {
        // Check if the number is prime
        if (isPrime(num)) {
            // Increment the count of prime numbers found
            primeCount++;
            // If the count is a multiple of K, multiply the product by the prime number
            if (primeCount % k === 0) {
                product *= num;
            }
        }
    }
    // Return the final product
    return product;
}

// Test cases
const arr1 = [2, 3, 5, 7, 11];
const k1 = 2;
console.log(productOfKthPrimes(arr1, k1)); // Output: 21

const arr2 = [41, 23, 12, 17, 18, 19];
const k2 = 2;
console.log(productOfKthPrimes(arr2, k2)); // Output: 437

Output
21
437


Efficient approach: Create a sieve which will store whether a number is prime or not. Then, it can be used to check a number against prime in O(1) time. In this way, we only have to keep track of every K’th prime number and maintain the running product.

Below is the implementation of the above approach: 

C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000000
bool prime[MAX + 1];
void SieveOfEratosthenes()
{
    // Create a boolean array "prime[0..n]"
    // and initialize all the entries as true.
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    memset(prime, true, sizeof(prime));

    // 0 and 1 are not prime numbers
    prime[1] = false;
    prime[0] = false;

    for (int p = 2; p * p <= MAX; 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; i += p)
                prime[i] = false;
        }
    }
}

// compute the answer
void productOfKthPrimes(int arr[], int n, int k)
{
    // count of primes
    int c = 0;

    // product of the primes
    long long int product = 1;

    // traverse the array
    for (int i = 0; i < n; i++) {

        // if the number is a prime
        if (prime[arr[i]]) {

            // increase the count
            c++;

            // if it is the K'th prime
            if (c % k == 0) {
                product *= arr[i];
                c = 0;
            }
        }
    }
    cout << product << endl;
}

// Driver code
int main()
{

    // create the sieve
    SieveOfEratosthenes();

    int n = 5, k = 2;

    int arr[n] = { 2, 3, 5, 7, 11 };

    productOfKthPrimes(arr, n, k);

    return 0;
}
Java
// Java implementation of the approach

class GFG
{
static int MAX=1000000;
static boolean[] prime=new boolean[MAX + 1];
static void SieveOfEratosthenes()
{
    // Create a boolean array "prime[0..n]"
    // and initialize all the entries as true.
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    //memset(prime, true, sizeof(prime));

    // 0 and 1 are not prime numbers
    prime[1] = true;
    prime[0] = true;

    for (int p = 2; p * p <= MAX; p++) {

        // If prime[p] is not changed, 
        // then it is a prime
        if (prime[p] == false) {

            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = true;
        }
    }
}

// compute the answer
static void productOfKthPrimes(int arr[], int n, int k)
{
    // count of primes
    int c = 0;

    // product of the primes
    int product = 1;

    // traverse the array
    for (int i = 0; i < n; i++) {

        // if the number is a prime
        if (!prime[arr[i]]) {

            // increase the count
            c++;

            // if it is the K'th prime
            if (c % k == 0) {
                product *= arr[i];
                c = 0;
            }
        }
    }
    System.out.println(product);
}

// Driver code
public static void main(String[] args)
{

    // create the sieve
    SieveOfEratosthenes();

    int n = 5, k = 2;
 
    int[] arr=new int[]{ 2, 3, 5, 7, 11 };
 
    productOfKthPrimes(arr, n, k);
}
}
// This code is contributed by mits
Python
# Python 3 implementation of the approach

MAX = 1000000
prime = [True]*(MAX + 1)
def SieveOfEratosthenes():
    
    # Create a boolean array "prime[0..n]"
    # and initialize all the entries as true.
    # A value in prime[i] will finally be false
    # if i is Not a prime, else true.
    

    # 0 and 1 are not prime numbers
    prime[1] = False;
    prime[0] = False;

    p = 2
    while p * p <= MAX:

        # If prime[p] is not changed, 
        # then it is a prime
        if (prime[p] == True):

            # Update all multiples of p
            for i in range(p * 2, MAX+1, p):
                prime[i] = False
        p+=1

# compute the answer
def productOfKthPrimes(arr, n, k):

    # count of primes
    c = 0

    # product of the primes
    product = 1

    # traverse the array
    for i in range( n):

        # if the number is a prime
        if (prime[arr[i]]):

            # increase the count
            c+=1

            # if it is the K'th prime
            if (c % k == 0) :
                product *= arr[i]
                c = 0

    print(product)

# Driver code
if __name__ == "__main__":

    # create the sieve
    SieveOfEratosthenes()

    n = 5
    k = 2

    arr = [ 2, 3, 5, 7, 11 ]

    productOfKthPrimes(arr, n, k)

# This code is contributed by ChitraNayal
C#
// C# implementation of the approach
class GFG
{
static int MAX = 1000000;
static bool[] prime = new bool[MAX + 1];
static void SieveOfEratosthenes()
{
    // Create a boolean array "prime[0..n]"
    // and initialize all the entries as 
    // true. A value in prime[i] will 
    // finally be false if i is Not a prime,
    // else true.

    // 0 and 1 are not prime numbers
    prime[1] = true;
    prime[0] = true;

    for (int p = 2; p * p <= MAX; p++)
    {

        // If prime[p] is not changed, 
        // then it is a prime
        if (prime[p] == false) 
        {

            // Update all multiples of p
            for (int i = p * 2;
                     i <= MAX; i += p)
                prime[i] = true;
        }
    }
}

// compute the answer
static void productOfKthPrimes(int[] arr,
                               int n, int k)
{
    // count of primes
    int c = 0;

    // product of the primes
    int product = 1;

    // traverse the array
    for (int i = 0; i < n; i++) 
    {

        // if the number is a prime
        if (!prime[arr[i]]) 
        {

            // increase the count
            c++;

            // if it is the K'th prime
            if (c % k == 0) 
            {
                product *= arr[i];
                c = 0;
            }
        }
    }
    System.Console.WriteLine(product);
}

// Driver code
static void Main()
{

    // create the sieve
    SieveOfEratosthenes();

    int n = 5, k = 2;

    int[] arr=new int[]{ 2, 3, 5, 7, 11 };

    productOfKthPrimes(arr, n, k);
}
}

// This code is contributed by mits
Javascript
<script>
// Javascript implementation of the approach

let MAX = 1000000;
let prime = new Array(MAX + 1);
function SieveOfEratosthenes() {
    // Create a boolean array "prime[0..n]"
    // and initialize all the entries as true.
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    prime.fill(true)

    // 0 and 1 are not prime numbers
    prime[1] = false;
    prime[0] = false;

    for (let p = 2; p * p <= MAX; p++) {

        // If prime[p] is not changed,
        // then it is a prime
        if (prime[p] == true) {

            // Update all multiples of p
            for (let i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
}

// compute the answer
function productOfKthPrimes(arr, n, k) {
    // count of primes
    let c = 0;

    // product of the primes
    let product = 1;

    // traverse the array
    for (let i = 0; i < n; i++) {

        // if the number is a prime
        if (prime[arr[i]]) {

            // increase the count
            c++;

            // if it is the K'th prime
            if (c % k == 0) {
                product *= arr[i];
                c = 0;
            }
        }
    }
    document.write(product + "<br>");
}

// Driver code

// create the sieve
SieveOfEratosthenes();

let n = 5, k = 2;

let arr = [2, 3, 5, 7, 11];

productOfKthPrimes(arr, n, k);

// This code is contributed by gfgking.
</script>

Output
21

Complexity Analysis:

  • Time Complexity : O(n)
  • Auxiliary Space: O(MAX)


Contact Us