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:
Check if Array Elemnts can be Made Equal with Given Operations
Next article icon

Check if elements of array can be made equal by multiplying given prime numbers

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

Given an array of integers and an array of prime numbers. The task is to find if it is possible to make all the elements of integer array equal by multiplying one or more elements from prime given array of prime numbers.
Examples: 
 

Input : arr[]   = {50, 200}          prime[] = {2, 3} Output : Yes We can multiply 50 with 2 two times to make both elements of arr[] equal  Input : arr[]   = {3, 4, 5, 6, 2}          prime[] = {2, 3} Output : No

 

We find LCM of all array elements. All elements can be made equal only if it is possible to convert all numbers to LCM. So we find the multiplier for each element so that we can make that element equal to LCM by multiplying that number. After that we find if numbers from given primes can form given multiplier.
Algorithm- 
Step 1: Find LCM of all numbers in the array O(n)
Step 2 : For each number arr[i] 
——– Divide LCM by arr[i] 
——– Use each input prime number to divide the result to remove all factors of input prime numbers (can use modulo to check divisibility) 
——– If left over number is not 1, return false; 
Step 3 : Return true
Below is the implementation of above algorithm.
 

C++




// C++ program to find if array elements can
// be made same
#include<bits/stdc++.h>
using namespace std;
 
// To calculate LCM of whole array
int lcmOfArray(int arr[], int n)
{
    int ans = arr[0];
    for (int i=1; i<n; i++)
        ans = (arr[i]*ans)/__gcd(arr[i], ans);
    return ans;
}
 
// function to check possibility if we can make
// all element same or not
bool checkArray(int arr[], int prime[], int n, int m)
{
    // Find LCM of whole array
    int lcm = lcmOfArray(arr,n);
 
    // One by one check if value of lcm / arr[i]
    // can be formed using prime numbers.
    for (int i=0; i<n; i++)
    {
        // divide each element of array by LCM
        int val = lcm/arr[i];
 
        // Use each input prime number to divide
        // the result to remove all factors of
        // input prime numbers
        for (int j=0; j<m && val!=1; j++)
            while (val % prime[j] == 0)
                val = val/prime[j];
 
        // If the remaining value is not 1, then
        // it is not possible to make all elements
        // same.
        if (val != 1)
          return false;
    }
 
    return true;
}
 
// Driver code
int main()
{
    int arr[] = {50, 200};
    int prime[] = {2, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    int m = sizeof(prime)/sizeof(prime[0]);
 
    checkArray(arr, prime, n, m)? cout << "Yes" :
                                  cout << "No";
    return 0;
}
 
 

Java




// Java program to find if array
// elements can be made same
 
class GFG
{
    static int ___gcd(int a, int b)
    {
        // Everything divides 0
        if (a == 0 || b == 0)
        return 0;
     
        // base case
        if (a == b)
            return a;
     
        // a is greater
        if (a > b)
            return ___gcd(a - b, b);
        return ___gcd(a, b - a);
    }
     
    // To calculate LCM of whole array
    static int lcmOfArray(int arr[], int n)
    {
        int ans = arr[0];
        for (int i = 1; i < n; i++)
            ans = (arr[i] * ans)/ ___gcd(arr[i], ans);
        return ans;
    }
     
    // function to check possibility if we can make
    // all element same or not
    static boolean checkArray(int arr[], int prime[],
                                          int n, int m)
    {
        // Find LCM of whole array
        int lcm = lcmOfArray(arr,n);
     
        // One by one check if value of lcm / arr[i]
        // can be formed using prime numbers.
        for (int i = 0; i < n; i++)
        {
            // divide each element of array by LCM
            int val = lcm / arr[i];
     
            // Use each input prime number to divide
            // the result to remove all factors of
            // input prime numbers
            for (int j = 0; j < m && val != 1; j++)
                while (val % prime[j] == 0)
                    val = val / prime[j];
     
            // If the remaining value is not 1, then
            // it is not possible to make all elements
            // same.
            if (val != 1)
            return false;
        }
     
        return true;
    }
     
    // Driver code
    public static void main (String[] args)
    {
        int arr[] = {50, 200};
        int prime[] = {2, 3};
        int n = arr.length;
        int m = prime.length;
     
        if(checkArray(arr, prime, n, m))
        System.out.print("Yes");
        else
        System.out.print("No");
    }
}
 
// This code is contributed by Anant Agarwal.
 
 

Python3




# Python  program to find
# if array elements can
# be made same
 
def ___gcd(a,b):
     
    # Everything divides 0
    if (a == 0 or b == 0):
        return 0
  
    # base case
    if (a == b):
        return a
  
    # a is greater
    if (a > b):
        return ___gcd(a-b, b)
    return ___gcd(a, b-a)
 
# To calculate LCM of whole array
def lcmOfArray(arr,n):
     
    ans = arr[0]
    for i in range(1,n):
        ans = (arr[i]*ans)/___gcd(arr[i], ans)
    return ans
 
  
# function to check possibility
# if we can make
# all element same or not
def checkArray(arr, prime, n, m):
 
    # Find LCM of whole array
    lcm = lcmOfArray(arr, n)
  
    # One by one check if
    # value of lcm / arr[i]
    # can be formed using prime numbers.
    for i in range(n):
 
        # divide each element
        # of array by LCM
        val = lcm/arr[i]
  
        # Use each input prime
        # number to divide
        # the result to remove
        # all factors of
        # input prime numbers
        for j in range(m and val!=1):
            while (val % prime[j] == 0):
                val = val/prime[j]
  
        # If the remaining value
        # is not 1, then
        # it is not possible to
        # make all elements
        # same.
        if (val != 1):
            return 0
  
    return 1
 
# Driver code
arr = [50, 200]
prime = [2, 3]
n = len(arr)
m = len(prime)
  
if(checkArray(arr, prime, n, m)):
    print("Yes")
else:
    print("No")
 
# This code is contributed
# by Anant Agarwal.
 
 

C#




// C# program to find if array
// elements can be made same
using System;
 
class GFG {
     
    static int ___gcd(int a, int b)
    {
         
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
     
        // base case
        if (a == b)
            return a;
     
        // a is greater
        if (a > b)
            return ___gcd(a - b, b);
             
        return ___gcd(a, b - a);
    }
     
    // To calculate LCM of whole array
    static int lcmOfArray(int []arr, int n)
    {
        int ans = arr[0];
         
        for (int i = 1; i < n; i++)
            ans = ((arr[i] * ans) /
                       ___gcd(arr[i], ans));
        return ans;
    }
     
    // function to check possibility if
    // we can make all element same or not
    static bool checkArray(int []arr,
                 int []prime, int n, int m)
    {
         
        // Find LCM of whole array
        int lcm = lcmOfArray(arr, n);
     
        // One by one check if value of
        // lcm / arr[i] can be formed
        // using prime numbers.
        for (int i = 0; i < n; i++)
        {
             
            // divide each element of
            // array by LCM
            int val = lcm / arr[i];
     
            // Use each input prime number
            // to divide the result to
            // remove all factors of
            // input prime numbers
            for (int j = 0; j < m &&
                                val != 1; j++)
                while (val % prime[j] == 0)
                    val = val / prime[j];
     
            // If the remaining value is not 1,
            // then it is not possible to make
            // all elements same.
            if (val != 1)
                return false;
        }
     
        return true;
    }
     
    // Driver code
    public static void Main ()
    {
        int []arr = {50, 200};
        int []prime = {2, 3};
        int n = arr.Length;
        int m = prime.Length;
     
        if(checkArray(arr, prime, n, m))
            Console.Write("Yes");
        else
            Console.Write("No");
    }
}
 
// This code is contributed by nitin mittal
 
 

PHP




<?php
// PHP program to find if
// array elements can be
// made same
 
function ___gcd($a, $b)
{
     
    // Everything divides 0
    if ($a == 0 || $b == 0)
        return 0;
 
    // base case
    if ($a == $b)
        return $a;
 
    // a is greater
    if ($a > $b)
        return ___gcd($a - $b, $b);
         
    return ___gcd($a, $b - $a);
}
 
// To calculate LCM
// of whole array
function lcmOfArray($arr, $n)
{
    $ans = $arr[0];
     
    for ($i = 1; $i < $n; $i++)
        $ans = (($arr[$i] * $ans) /
                ___gcd($arr[$i], $ans));
    return $ans;
}
 
// function to check
// possibility if we
// can make all element
// same or not
function checkArray($arr, $prime,
                    $n, $m)
{
     
    // Find LCM of
    // whole array
    $lcm = lcmOfArray($arr, $n);
 
    // One by one check if
    // value of lcm / arr[i]
    // can be formed using
    // prime numbers.
    for ($i = 0; $i < $n; $i++)
    {
         
        // divide each element
        // of array by LCM
        $val = $lcm / $arr[$i];
 
        // Use each input prime
        // number to divide the
        // result to remove all
        // factors of input prime
        // numbers
        for ($j = 0; $j < $m &&
                     $val != 1; $j++)
            while ($val % $prime[$j] == 0)
                $val = $val / $prime[$j];
 
        // If the remaining value
        // is not 1, then it is
        // not possible to make
        // all elements same.
        if ($val != 1)
            return false;
    }
 
    return true;
}
 
// Driver code
$arr = array(50, 200);
$prime = array(2, 3);
$n = sizeof($arr);
$m = sizeof($prime);
 
if(checkArray($arr, $prime,
              $n, $m))
    echo "Yes";
else
    echo "No";
 
// This code is contributed
// by akt_mit
?>
 
 

Javascript




<script>
 
// Javascript program to find if array
// elements can be made same
 
    function ___gcd(a, b)
    {
        // Everything divides 0 
        if (a == 0 || b == 0)
        return 0;
       
        // base case
        if (a == b)
            return a;
       
        // a is greater
        if (a > b)
            return ___gcd(a - b, b);
        return ___gcd(a, b - a);
    } 
       
    // To calculate LCM of whole array
    function lcmOfArray(arr, n)
    {
        let ans = arr[0];
        for (let i = 1; i < n; i++)
            ans = (arr[i] * ans)/ ___gcd(arr[i], ans);
        return ans;
    }
       
    // function to check possibility if we can make
    // all element same or not
    function checkArray(arr, prime, n, m)
    {
        // Find LCM of whole array
        let lcm = lcmOfArray(arr,n);
       
        // One by one check if value of lcm / arr[i]
        // can be formed using prime numbers.
        for (let i = 0; i < n; i++)
        {
            // divide each element of array by LCM
            let val = lcm / arr[i];
       
            // Use each input prime number to divide
            // the result to remove all factors of
            // input prime numbers
            for (let j = 0; j < m && val != 1; j++)
                while (val % prime[j] == 0)
                    val = val / prime[j];
       
            // If the remaining value is not 1, then
            // it is not possible to make all elements
            // same.
            if (val != 1)
            return false;
        }
       
        return true;
    }
 
// Driver Code
     
        let arr = [50, 200];
        let prime = [2, 3];
        let n = arr.length;
        let m = prime.length;
       
        if(checkArray(arr, prime, n, m))
        document.write("Yes");
        else
        document.write("No");
         
</script>
 
 

Output: 

Yes

Time Complexity: O(m x n) 
Auxiliary Space: O(1)

 



Next Article
Check if Array Elemnts can be Made Equal with Given Operations

A

Aarti_Rathi and Niteesh kumar
Improve
Article Tags :
  • DSA
  • Mathematical
  • GCD-LCM
Practice Tags :
  • Mathematical

Similar Reads

  • Check if Array Elemnts can be Made Equal with Given Operations
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
    6 min read
  • Check if Arrays can be made equal by Replacing elements with their number of Digits
    Given two arrays A[] and B[] of length N, the task is to check if both arrays can be made equal by performing the following operation at most K times: Choose any index i and either change Ai to the number of digits Ai have or change Bi to the number of digits Bi have. Examples: Input: N = 4, K = 1,
    10 min read
  • Check if Array elements can be made equal by adding unit digit to the number
    Given an array arr[] of N integers, the task is to check whether it is possible to make all the array elements identical by applying the following option any number of times: Choose any number and add its unit digit to it. Examples: Input: arr[] = {1, 2, 4, 8, 24}Output: PossibleExplanation: For 1:
    7 min read
  • Check if array elements can become same using one external number
    Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X: Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.The task is to check whether there exists a number X,
    11 min read
  • Check if each element of the given array is the product of exactly K prime numbers
    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 pr
    9 min read
  • Count array elements having modular inverse under given prime number P equal to itself
    Given an array arr[] of size N and a prime number P, the task is to count the elements of the array such that modulo multiplicative inverse of the element under modulo P is equal to the element itself. Examples: Input: arr[] = {1, 6, 4, 5}, P = 7Output: 2Explanation:Modular multiplicative inverse of
    5 min read
  • Find Prime number just less than and just greater each element of given Array
    Given an integer array A[] of size N, the task is to find the prime numbers just less and just greater than A[i] (for all 0<=i<N). Examples: Input: A={17, 28}, N=2Output:13 1923 29Explanation:13 is the prime number just less than 17.19 is the prime number just greater than 17.23 is the prime n
    15+ min read
  • Check if possible to make Array sum equal to Array product by replacing exactly one element
    Given an array arr[] consisting of N non-negative integers, the task is to check if it is possible to make the sum of the array equal to the product of the array element by replacing exactly one array element with any non-negative integer. Examples: Input: arr[] = {1, 3, 4}Output: YesExplanation:Rep
    7 min read
  • Nearest prime number in the array of every array element
    Given an integer array arr[] consisting of N integers, the task is to find the nearest Prime Number in the array for every element in the array. If the array does not contain any prime number, then print -1. Examples: Input: arr[] = {1, 2, 3, 1, 6} Output: 2 2 3 3 3 Explanation: For the subarray {1,
    11 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
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