Check if the given array contains all the divisors of some integer in Python


Suppose we have an array nums, we have to check whether this array is containing all of the divisors of some integer or not.

So, if the input is like nums = [1, 2, 3, 4, 6, 8, 12, 24], then the output will be True as these are the divisors of 24.

To solve this, we will follow these steps −

  • maximum := maximum of nums
  • temp := a new list
  • for i in range 1 to square root of maximum, do
    • if maximum is divisible by i, then
      • insert i at the end of temp
      • if quotient of (maximum / i) is not same as i, then
        • insert quotient of (maximum / i) at the end of temp
    • if size of temp is not same as size of nums, then
      • return False
    • sort the list nums and temp
    • for i in range 0 to size of nums - 1, do
      • if temp[i] is not same as nums[i], then
        • return False
  • return True

Let us see the following implementation to get better understanding −

Example Code

Live Demo

from math import sqrt
 
def solve(nums):
   maximum = max(nums)
 
   temp = []
   for i in range(1,int(sqrt(maximum))+1):
      if maximum % i == 0:
         temp.append(i)
         if (maximum // i != i):
           temp.append(maximum // i)
 
   if len(temp) != len(nums):
      return False
 
   nums.sort()
   temp.sort()
 
   for i in range(len(nums)):
      if temp[i] != nums[i]:
         return False
   return True
   
nums = [1, 2, 3, 4, 6, 8, 12, 24]
print(solve(nums))

Input

[1, 2, 3, 4, 6, 8, 12, 24]

Output

True

Updated on: 15-Jan-2021

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements