Product of all prime numbers in an Array

Given an array arr[] of N positive integers. The task is to write a program to find the product of all the prime numbers of the given array.

Examples

Input: arr[] = {1, 3, 4, 5, 7} 
Output: 105 
There are three primes, 3, 5 and 7 whose product = 105.

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

Naïve Approach:

A simple solution is to traverse the array and keep checking for every element if it is prime or not and calculate the product of the prime element at the same time.

Step-by-step approach:

  • Create a function is_prime() to check if a number is prime.
  • Iterate from 2 to the square root of the number, checking for factors.
    • Return false if any factor is found, indicating the number is not prime.
    • If no factors are found, return true, indicating the number is prime.
  • Create a function product_of_primes() to find the product of prime numbers in an array.
    • Initialize a product variable to 1.
    • Iterate through each element of the array.
      • Check if each element is prime using is_prime() function.
      • If it’s prime, multiply it with the running product.
      • Return the final product.

Below is the implementation of the above approach:

C++
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;

bool is_prime(int number)
{
    // Prime numbers are greater than 1
    if (number <= 1) {
        return false;
    }

    // Check for factors from 2 to the square root of the
    // number
    for (int i = 2; i <= sqrt(number); ++i) {
        if (number % i == 0) {
            return false;
        }
    }

    // If no factors are found, the number is prime
    return true;
}

// Function to find the product of all prime numbers in the
// array
int product_of_primes(const vector<int>& arr)
{
    int product = 1;
    for (int num : arr) {
        if (is_prime(num)) {
            product *= num;
        }
    }
    return product;
}

int main()
{
    vector<int> arr2 = { 1, 2, 3, 4, 5, 6, 7 };
    cout << "Product: " << product_of_primes(arr2)
         << endl; // Output: 210

    return 0;
}
Java
public class Main {
    // Function to check if a number is prime
    static boolean isPrime(int number)
    {
        // Prime numbers are greater than 1
        if (number <= 1) {
            return false;
        }

        // Check for factors from 2 to the square root of
        // the number
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                return false;
            }
        }

        // If no factors are found, the number is prime
        return true;
    }

    // Function to find the product of all prime numbers in
    // the array
    static int productOfPrimes(int[] arr)
    {
        int product = 1;
        for (int num : arr) {
            if (isPrime(num)) {
                product *= num;
            }
        }
        return product;
    }

    public static void main(String[] args)
    {
        int[] arr2 = { 1, 2, 3, 4, 5, 6, 7 };
        System.out.println(
            "Product: "
            + productOfPrimes(arr2)); // Output: 210
    }
}
Python
def is_prime(number):
    # Prime numbers are greater than 1
    if number <= 1:
        return False

    # Check for factors from 2 to the square root of the number
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False

    # If no factors are found, the number is prime
    return True

# Function to find the product of all prime numbers in the array


def product_of_primes(arr):
    product = 1
    for num in arr:
        if is_prime(num):
            product *= num
    return product


arr2 = [1, 2, 3, 4, 5, 6, 7]
print("Product:", product_of_primes(arr2))  # Output: 210
JavaScript
// Function to check if a number is prime
function isPrime(number) {
    // Prime numbers are greater than 1
    if (number <= 1) {
        return false;
    }

    // Check for factors from 2 to the square root of the number
    for (let i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
            return false;
        }
    }

    // If no factors are found, the number is prime
    return true;
}

// Function to find the product of all prime numbers in the array
function productOfPrimes(arr) {
    let product = 1;
    for (let num of arr) {
        if (isPrime(num)) {
            product *= num;
        }
    }
    return product;
}

// Main function
const arr2 = [1, 2, 3, 4, 5, 6, 7];
console.log("Product: " + productOfPrimes(arr2)); // Output: 210

Output
Product: 105
Product: 210

Product of all prime numbers in an Array using the sieve of Eratosthenes:

Generate all primes up to the maximum element of the array using the sieve of Eratosthenes and store them in a hash. Now traverse the array and find the product of those elements which are prime using the sieve.

Step-by-step approach:

  • Create a function primeProduct() to find the product of prime numbers in the given array.
  • Find the maximum value in the array.
  • Initialize a boolean vector prime to mark prime numbers up to max_val.
  • Mark 0 and 1 as not prime.
  • Use the Sieve of Eratosthenes algorithm to mark non-prime numbers in the vector.
  • Iterate through the array, multiplying elements that correspond to prime numbers.
  • Return the final product.

Below is the implementation of the above approach: 

C++
// CPP program to find product of
// primes in given array.
#include <bits/stdc++.h>
using namespace std;

// Function to find the product of prime numbers
// in the given array
int primeProduct(int arr[], int n)
{
    // 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
    // Create a boolean array "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);

    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    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;
        }
    }

    // Product all primes in arr[]
    int prod = 1;
    for (int i = 0; i < n; i++)
        if (prime[arr[i]])
            prod *= arr[i];

    return prod;
}

// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << primeProduct(arr, n);

    return 0;
}
Java
// Java program to find product of
// primes in given array.
import java.util.*;

class GFG 
{

// Function to find the product of prime numbers
// in the given array
static int primeProduct(int arr[], int n)
{
    // Find maximum value in the array
    int max_val = Arrays.stream(arr).max().getAsInt();

    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    Vector<Boolean> prime = new Vector<Boolean>(max_val + 1);
    for(int i = 0; i < max_val + 1; i++)
        prime.add(i, Boolean.TRUE);

    // Remaining part of SIEVE
    prime.add(0, Boolean.FALSE);
    prime.add(1, Boolean.FALSE);
    for (int p = 2; p * p <= max_val; p++)
    {

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

            // Update all multiples of p
            for (int i = p * 2; i <= max_val; i += p)
                prime.add(i, Boolean.FALSE);
        }
    }

    // Product all primes in arr[]
    int prod = 1;
    for (int i = 0; i < n; i++)
        if (prime.get(arr[i]))
            prod *= arr[i];

    return prod;
}

// Driver code
public static void main(String[] args) 
{
    int arr[] = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.length;

    System.out.print(primeProduct(arr, n));
}
}

// This code has been contributed by 29AjayKumar
Python
# Python3 program to find product of
# primes in given array
import math as mt

# function to find the product of prime
# numbers in the given array
def primeProduct(arr, n):
    
    # find the maximum value in the array
    max_val = max(arr)
    
    # USE SIEVE TO FIND ALL PRIME NUMBERS 
    # LESS THAN OR EQUAL TO max_val
    # Create a boolean array "prime[0..n]". A
    # value in prime[i] will finally be false
    # if i is Not a prime, else true.
    prime = [True for i in range(max_val + 1)]
    
    # remaining part of SIEVE
    prime[0] = False
    prime[1] = False
    
    for p in range(mt.ceil(mt.sqrt(max_val))):
        
        # Remaining part of SIEVE
        
        # if prime[p] is not changed, 
        # than it is prime
        if prime[p]:
            
            # update all multiples of p
            for i in range(p * 2, max_val + 1, p):
                prime[i] = False
    
    # product all primes in arr[]
    prod = 1
    
    for i in range(n):
        if prime[arr[i]]:
            prod *= arr[i]
    
    return prod

# Driver code
arr = [1, 2, 3, 4, 5, 6, 7]

n = len(arr)

print(primeProduct(arr, n))

# This code is contributed 
# by Mohit kumar 29
                
C#
// C# program to find product of
// primes in given array.
using System;
using System.Linq;
using System.Collections.Generic;

class GFG 
{

// Function to find the product of prime numbers
// in the given array
static int primeProduct(int []arr, int n)
{
    // Find maximum value in the array
    int max_val = arr.Max();

    // USE SIEVE TO FIND ALL PRIME NUMBERS LESS
    // THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    List<bool> prime = new List<bool>(max_val + 1);
    for(int i = 0; i < max_val + 1; i++)
        prime.Insert(i, true);

    // Remaining part of SIEVE
    prime.Insert(0, false);
    prime.Insert(1, false);
    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.Insert(i, false);
        }
    }

    // Product all primes in arr[]
    int prod = 1;
    for (int i = 0; i < n; i++)
        if (prime[arr[i]])
            prod *= arr[i];

    return prod;
}

// Driver code
public static void Main() 
{
    int []arr = { 1, 2, 3, 4, 5, 6, 7 };
    int n = arr.Length;

    Console.Write(primeProduct(arr, n));
}
}

/* This code contributed by PrinciRaj1992 */
Javascript
<script>
// Javascript program to find product of
// primes in given array.

// Function to find the product of
// prime numbers in the given array
function primeProduct(arr, n)
{
    // Find maximum value in the array
    let max_val = arr.sort((a, b) => b - a)[0];

    // USE SIEVE TO FIND ALL PRIME NUMBERS
    // LESS THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]".
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    let prime = new Array(max_val + 1).fill(true);
    
    // Remaining part of SIEVE
    prime[0] = false;
    prime[1] = false;
    for (let 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 (let i = p * 2;
                i <= max_val; i += p)
                prime[i]= false;
        }
    }

    // Product all primes in arr[]
    let prod = 1;
    for (let i = 0; i < n; i++)
        if (prime[arr[i]])
            prod *= arr[i];

    return prod;
}

// Driver code
let arr = new Array(1, 2, 3, 4, 5, 6, 7);
let n = arr.length;

document.write(primeProduct(arr, n));

// This code contributed by _Saurabh_Jaiswal.
</script>
PHP
<?php
// PHP program to find product of
// primes in given array.

// Function to find the product of 
// prime numbers in the given array
function primeProduct($arr, $n)
{
    // Find maximum value in the array
    $max_val = max($arr);

    // USE SIEVE TO FIND ALL PRIME NUMBERS 
    // LESS THAN OR EQUAL TO max_val
    // Create a boolean array "prime[0..n]". 
    // A value in prime[i] will finally be false
    // if i is Not a prime, else true.
    $prime = array_fill(0, $max_val + 1, True);
    
    // Remaining part of SIEVE
    $prime[0] = false;
    $prime[1] = false;
    for ($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 ($i = $p * 2; 
                 $i <= $max_val; $i += $p)
                $prime[$i]= false;
        }
    }

    // Product all primes in arr[]
    $prod = 1;
    for ($i = 0; $i < $n; $i++)
        if ($prime[$arr[$i]])
            $prod *= $arr[$i];

    return $prod;
}

// Driver code
$arr = array(1, 2, 3, 4, 5, 6, 7);
$n = sizeof($arr);

echo(primeProduct($arr, $n));

// This code contributed by Code_Mech 
?>

Output
210


Contact Us