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

PythonServer Side ProgrammingProgramming

Suppose we have two arrays, one is nums and another one is primes. We have to check whether it is possible to make all the elements of nums equal by multiplying one or more prime numbers from primes array.

So, if the input is like nums = [25, 100] primes = [2, 5], then the output will be True as we can multiply 25 with 2 twice to get 100 then all elements are same.

To solve this, we will follow these steps −

  • lcm_arr := LCM of all elements in nums
  • for i in range 0 to size of nums - 1, do
    • val := lcm_arr/nums[i]
    • if size of primes is not 0 and val is not 1, then
      • while val mod primes[0] is 0, do
        • val := val/primes[j]
    • if val is not same as 1, then
      • return False
  • return True

Example

Let us see the following implementation to get better understanding −

from math import gcd
def array_lcm(nums):
   ans = nums[0]
   for i in range(1,len(nums)):
      ans = (nums[i]*ans)/gcd(nums[i], ans)
   return ans
def solve(nums, primes):
   lcm_arr = array_lcm(nums)
   for i in range(len(nums)):
      val = lcm_arr/nums[i]
      for j in range(len(primes) and val != 1):
         while (val % primes[j] == 0):
            val = val/primes[j]
      if (val != 1):
         return False
   return True
nums = [25, 100]
primes = [2, 5]
print(solve(nums, primes))

Input

[25, 100], [2, 5]

Output

True
raja
Published on 18-Jan-2021 16:53:58
Advertisements