Program to find number of values factors of two set of numbers

PythonServer Side ProgrammingProgramming

Suppose we have two arrays called nums1 and nums2. We have to find the number of values that satisfy the following conditions −

  • The elements in nums1 are the factors of the elements which are being selected

  • The elements which are selected is a factor of all of the elements of nums2

So, if the input is like nums1 = [3,9] nums2 = [27, 81], then the output will be 2 because the numbers are 9 and 27, because

  • 9 mod 3 = 0

  • 9 mod 9 = 0

  • 27 mod 9 = 0

  • 81 mod 9 = 0

  • 27 mod 3 = 0

  • 27 mod 9 = 0

  • 27 mod 27 = 0

  • 81 mod 27 = 0.

To solve this, we will follow these steps −

  • count := 0
  • for i in range 1 to 100, do
    • flag := True
    • for each j in nums1, do
      • if i mod j is not 0, then
        • flag := False
        • come out from the loop
    • if flag is true, then
      • for each k in nums2, do
        • if k mod i is not 0, then
          • flag := False
          • come out from the loop
    • if flag is true, then
      • count := count + 1
  • return count

Example

Let us see the following implementation to get better understanding

def solve(nums1, nums2):
   count = 0
   for i in range(1,101):
      flag = True
      for j in nums1:
         if i%j != 0:
            flag = False
            break
      if flag:
         for k in nums2:
            if k%i!=0:
               flag = False
               break
      if flag:
         count+=1
         return count

nums1 = [3,9]
nums2 = [27, 81]
print(solve(nums1, nums2))

Input

[3,9], [27, 81]

Output

1
raja
Updated on 12-Oct-2021 09:33:33

Advertisements