Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Find the array element having equal count of Prime Numbers on its left and right
Next article icon

Check if each element of the given array is the product of exactly K prime numbers

Last Updated : 21 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of numbers [Tex]A = \{a\textsubscript{1}, a\textsubscript{2} … a\textsubscript{n}\}     [/Tex]and the value of [Tex]k     [/Tex], check if each number [Tex]a\textsubscript{i} \in A     [/Tex]can be expressed as the product of exactly [Tex]k     [/Tex]prime numbers. For every element of the array print ‘YES’ if the condition is satisfied, else print ‘NO’.
Note: Repeating prime numbers may also be considered. For example, if k = 2, then n = 4 (=2*2) is a valid input.
Let’s consider the number 36. 36 can be factorised as 2*2*3*3. Hence, it is the product of 4 prime numbers. If k value is 4, then the output should be YES. For other values of k, output should be NO.
More Examples: 
 

Input: arr[] = {30, 8, 12}, K = 3 Output: YES, YES, YES 30 = 2*3*5 8 = 2*2*2 12 = 2*3*2 Input: arr[] = {30, 16, 32}, k = 5 Output: NO, NO, YES Only 32 can be represented as product of 5 prime numbers.


 


In this article, we shall check if the given number(s) can be expressed as the product of exactly k prime numbers. The underlying concept that we shall we be using is simply a variation of the Sieve of Eratosthenes.
Recommended: How to construct the Sieve of Eratosthenes
 

Key Difference: In the Sieve, instead of storing binary values (0 if number not prime, 1 if the number is prime), we can store how many (repeating) prime factors make up that number instead. This modification is done during its construction. 


The generalised procedure to create this modified sieve is as follows: 
 

  1. Create an array full of 0’s to store the list of consecutive integers (2, 3, 4 … 10^6).
  2. Let the value of i be set to 2 initially. This is our first prime number.
  3. Loop through all the multiples of i (2*i, 3*i … till 10^6) by storing its value as j. Proceed with steps 3 and 4.
  4. Calculate the number of times j can be factorised using i and store the result into the variable count.
  5. When the number j cannot be further factorised using i, increment the value of Sieve[j] by the count value.
  6. Finally, find the next prime number greater than i in the list of integers. If there is no such number then terminate the process. Else, follow from step 2 again.


Explanation with example:
STEP 1:
The initialised empty sieve array looks as illustrated below. For simplicity’s sake let’s only concentrate on indices 2 through 12. The values stored initially is 0 for all indices.
Now, the first prime number that we will take is 2. This is the value of i.
 


STEP 2:
Initialise variable j to hold the value of every subsequent multiple of i starting from 2*i, which in this case is 4.
 


STEP 3:
The third step involves the computation of the prime factorisation of j. More specifically, we are just interested in counting the number of occurrences of i when you factorise j.
The computation procedure is simple. Just divide the value of j with i until you get a number that is not divisible by i. Here, 4 can be divided by 2 twice. 4/2 yields 2 and 2/2 yields 1, which is not divisible by 2 and the loop stops. Hence, we update the value of Sieve[4] with the value of the count variable, which is 2.
 


STEP 4:
We can proceed with the other elements in a similar fashion. Next, the value of j is 6. 6 can only be divided by 2 once. Hence the value of Sieve[6] is 1.
 


 


The final computed Sieve array should look something like this. Note that any index storing the value 0 represents a number that is not the product of 2 or more prime numbers. This includes all prime numbers, 0 and 1.
The second thing to note is that we need to only check 
 


Below is the implementation of the above approach: 
 

C++

// C++ program to check if each element of
// the given array is a product of exactly
// K prime factors
 
#include <iostream>
#define MAX 1000000
using namespace std;
 
// initialise the global sieve array
int Sieve[MAX] = { 0 };
 
// Function to generate Sieve
void constructSieve()
{
    // NOTE: k value is necessarily more than 1
    // hence, 0, 1 and any prime number cannot be
    // represented as product of
    // two or more prime numbers
 
    for (int i = 2; i <= MAX; i++) {
        if (Sieve[i] == 0) {
            for (int j = 2 * i; j <= MAX; j += i) {
                int temp = j;
                while (temp > 1 && temp % i == 0) {
                    Sieve[j]++;
                    temp = temp / i;
                }
            }
        }
    }
}
 
// Function to check if each number of array
// satisfies the given condition
void checkElements(int A[], int n, int k)
{
    for (int i = 0; i < n; i++) {
        if (Sieve[A[i]] == k) {
            cout << "YES\n";
        }
        else {
            cout << "NO\n";
        }
    }
}
 
// Driver Code
int main()
{
    // first construct the sieve
    constructSieve();
 
    int k = 3;
    int A[] = { 12, 36, 42, 72 };
    int n = sizeof(A) / sizeof(int);
 
    checkElements(A, n, k);
 
    return 0;
}
                      
                       

Java

// Java program to check if each element of
// the given array is a product of exactly
// K prime factors
import java.util.*;
 
class GFG
{
 
    static int MAX = 1000000;
 
    // initialise the global sieve array
    static int[] Sieve = new int[MAX+1];
 
    // Function to generate Sieve
    static void constructSieve()
    {
        // NOTE: k value is necessarily more than 1
        // hence, 0, 1 and any prime number cannot be
        // represented as product of
        // two or more prime numbers
 
        for (int i = 2; i <= MAX; i++)
        {
            if (Sieve[i] == 0)
            {
                for (int j = 2 * i; j <= MAX; j += i)
                {
                    int temp = j;
                    while (temp > 1 && temp % i == 0)
                    {
                        Sieve[j]++;
                        temp = temp / i;
                    }
                }
            }
        }
    }
 
    // Function to check if each number of array
    // satisfies the given condition
    static void checkElements(int A[], int n, int k)
    {
        for (int i = 0; i < n; i++)
        {
            if (Sieve[A[i]] == k)
            {
                System.out.println("YES");
            }
            else
            {
                System.out.println("No");
            }
 
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // first construct the sieve
        constructSieve();
 
        int k = 3;
        int A[] = {12, 36, 42, 72};
        int n = A.length;
 
        checkElements(A, n, k);
    }
}
 
// This code contributed by Rajput-Ji
                      
                       

Python3

# Python3 program to check if each element of
# the given array is a product of exactly
# K prime factors
 
MAX = 1000000
 
# initialise the global sieve array
Sieve = [0]*(MAX + 1)
 
# Function to generate Sieve
def constructSieve() :
 
    # NOTE: k value is necessarily more than 1
    # hence, 0, 1 and any prime number cannot be
    # represented as product of
    # two or more prime numbers
 
    for i in range(2, MAX + 1) :
        if (Sieve[i] == 0) :
            for j in range(2*i, MAX + 1, i) :
                temp = j;
                while (temp > 1 and temp % i == 0) :
                    Sieve[j] += 1;
                    temp = temp // i;
         
 
# Function to check if each number of array
# satisfies the given condition
def checkElements(A, n, k) :
 
    for i in range(n) :
        if (Sieve[A[i]] == k) :
            print("YES");
             
        else :
            print("NO");
 
# Driver Code
if __name__ == "__main__" :
 
    # first construct the sieve
    constructSieve();
 
    k = 3;
    A = [ 12, 36, 42, 72 ];
    n = len(A);
 
    checkElements(A, n, k);
     
# This code is contributed by AnkitRai01
                      
                       

C#

// C# program to check if each element of
// the given array is a product of exactly
// K prime factors
using System;
 
class GFG
{
 
    static int MAX = 1000000;
 
    // initialise the global sieve array
    static int[] Sieve = new int[MAX+1];
 
    // Function to generate Sieve
    static void constructSieve()
    {
        // NOTE: k value is necessarily more than 1
        // hence, 0, 1 and any prime number cannot be
        // represented as product of
        // two or more prime numbers
 
        for (int i = 2; i <= MAX; i++)
        {
            if (Sieve[i] == 0)
            {
                for (int j = 2 * i; j <= MAX; j += i)
                {
                    int temp = j;
                    while (temp > 1 && temp % i == 0)
                    {
                        Sieve[j]++;
                        temp = temp / i;
                    }
                }
            }
        }
    }
 
    // Function to check if each number of array
    // satisfies the given condition
    static void checkElements(int []A, int n, int k)
    {
        for (int i = 0; i < n; i++)
        {
            if (Sieve[A[i]] == k)
            {
                Console.WriteLine("YES");
            }
            else
            {
                Console.WriteLine("No");
            }
 
        }
    }
 
    // Driver Code
    public static void Main()
    {
        // first construct the sieve
        constructSieve();
 
        int k = 3;
        int []A = {12, 36, 42, 72};
        int n = A.Length;
 
        checkElements(A, n, k);
    }
}
 
// This code contributed by anuj_67...
                      
                       

Javascript

<script>
 
// Javascript program to check if each element of
// the given array is a product of exactly
// K prime factors
 
const MAX = 1000000;
 
// initialise the global sieve array
let Sieve = new Array(MAX).fill(0);
 
// Function to generate Sieve
function constructSieve()
{
    // NOTE: k value is necessarily more than 1
    // hence, 0, 1 and any prime number cannot be
    // represented as product of
    // two or more prime numbers
 
    for (let i = 2; i <= MAX; i++) {
        if (Sieve[i] == 0) {
            for (let j = 2 * i; j <= MAX; j += i)
            {
                let temp = j;
                while (temp > 1 && temp % i == 0)
                {
                    Sieve[j]++;
                    temp = parseInt(temp / i);
                }
            }
        }
    }
}
 
// Function to check if each number of array
// satisfies the given condition
function checkElements(A, n, k)
{
    for (let i = 0; i < n; i++) {
        if (Sieve[A[i]] == k) {
            document.write("YES<br>");
        }
        else {
            document.write("NO<br>");
        }
    }
}
 
// Driver Code
 
    // first construct the sieve
    constructSieve();
 
    let k = 3;
    let A = [ 12, 36, 42, 72 ];
    let n = A.length;
 
    checkElements(A, n, k);
 
</script>
                      
                       

Output: 
YES NO YES NO

 

Time Complexity: O(n*log(logn)), where n is the length of the array A.
Space Complexity: O(MAX), where MAX is 106.
 



Next Article
Find the array element having equal count of Prime Numbers on its left and right

P

pararuna
Improve
Article Tags :
  • DSA
  • Mathematical
  • Arrays
  • number-theory
  • Prime Number
  • sieve
Practice Tags :
  • Arrays
  • Mathematical
  • number-theory
  • Prime Number
  • sieve

Similar Reads

  • Check if product of array containing prime numbers is a perfect square
    Given an array arr[] containing only prime numbers, the task is to check if the product of the array elements is a perfect square or not.Examples: Input: arr[] = {2, 2, 7, 7} Output: Yes 2 * 2 * 7 * 7 = 196 = 142Input: arr[] = {3, 3, 3, 5, 5} Output: No Naive approach: Multiply all the elements of t
    4 min read
  • Check if the given number K is enough to reach the end of an array
    Given an array arr[] of n elements and a number K. The task is to determine if it is possible to reach the end of the array by doing the below operations:Traverse the given array and, If any element is found to be non-prime then decrement the value of K by 1.If any element is prime then refill the v
    14 min read
  • Find the array element having equal count of Prime Numbers on its left and right
    Given an array arr[] consisting of N positive integers, the task is to find an index from the array having count of prime numbers present on its left and right are equal. Examples: Input: arr[] = {2, 3, 4, 7, 5, 10, 1, 8}Output: 2Explanation: Consider the index 2, then the prime numbers to its left
    13 min read
  • Check if the Product of all Array elements is a Perfect Square or not
    Given an array arr[] consisting of N positive integers, the task is to check if the product of all the elements of the given array arr[] is a perfect square or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: arr[] = {1, 4, 100}Output: YesExplanation: The product of al
    6 min read
  • Sum of array elements which are prime factors of a given number
    Given an array arr[] of size N and a positive integer K, the task is to find the sum of all array elements which are prime factors of K. Examples: Input: arr[] = {1, 2, 3, 5, 6, 7, 15}, K = 35Output: 12Explanation: From the given array, 5 and 7 are prime factors of 35. Therefore, required sum = 5 +
    8 min read
  • Check whether the sum of prime elements of the array is prime or not
    Given an array having N elements. The task is to check if the sum of prime elements of the array is prime or not. Examples: Input: arr[] = {1, 2, 3} Output: Yes As there are two primes in the array i.e. 2 and 3. So, the sum of prime is 2 + 3 = 5 and 5 is also prime. Input: arr[] = {2, 3, 2, 2} Outpu
    10 min read
  • 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
    12 min read
  • Numbers less than N which are product of exactly two distinct prime numbers
    Given a number [Tex]N [/Tex]. The task is to find all such numbers less than N and are a product of exactly two distinct prime numbers. For Example, 33 is the product of two distinct primes i.e 11 * 3, whereas numbers like 60 which has three distinct prime factors i.e 2 * 2 * 3 * 5.Note: These numbe
    8 min read
  • Product of all the elements in an array divisible by a given number K
    Given an array containing N elements and a number K. The task is to find the product of all such elements of the array which are divisible by K. Examples: Input : arr[] = {15, 16, 10, 9, 6, 7, 17} K = 3 Output : 810 Input : arr[] = {5, 3, 6, 8, 4, 1, 2, 9} K = 2 Output : 384 The idea is to traverse
    6 min read
  • Count the number of primes in the prefix sum array of the given array
    Given an array arr[] of N integers, the task is to count the number of primes in the prefix sum array of the given array. Examples: Input: arr[] = {1, 4, 8, 4} Output: 3 The prefix sum array is {1, 5, 13, 17} and the three primes are 5, 13 and 17. Input: arr[] = {1, 5, 2, 3, 7, 9} Output: 1 Approach
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences