Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if LCM of array elements is divisible by a prime number or not in Python
Suppose we have an array called nums and another value k, we have to check whether LCM of nums is divisible by k or not.
So, if the input is like nums = [12, 15, 10, 75] and k = 10, then the output will be True as the LCM of the array elements is 300, which is divisible by 10.
Mathematical Approach
The key insight is that if any element in the array is divisible by k, then the LCM of all elements will also be divisible by k. This is because LCM contains all prime factors of every element in the array.
Algorithm Steps
To solve this problem, we will follow these steps ?
- Iterate through each element in the array
- If any element is divisible by
k, return True - If no element is divisible by
k, return False
Example
Let us see the following implementation to get better understanding ?
def solve(nums, k):
for i in range(0, len(nums)):
if nums[i] % k == 0:
return True
return False
nums = [12, 15, 10, 75]
k = 10
print(solve(nums, k))
The output of the above code is ?
True
Alternative Approach Using Any()
We can also use Python's built-in any() function for a more concise solution ?
def solve_optimized(nums, k):
return any(num % k == 0 for num in nums)
nums = [12, 15, 10, 75]
k = 10
print(solve_optimized(nums, k))
True
Test with Different Examples
Let's test with more examples to verify our solution ?
def solve(nums, k):
for num in nums:
if num % k == 0:
return True
return False
# Test case 1: LCM divisible by k
test1 = [12, 15, 10, 75]
k1 = 10
print(f"nums = {test1}, k = {k1}: {solve(test1, k1)}")
# Test case 2: LCM not divisible by k
test2 = [7, 13, 17]
k2 = 5
print(f"nums = {test2}, k = {k2}: {solve(test2, k2)}")
# Test case 3: Single element
test3 = [20]
k3 = 4
print(f"nums = {test3}, k = {k3}: {solve(test3, k3)}")
nums = [12, 15, 10, 75], k = 10: True nums = [7, 13, 17], k = 5: False nums = [20], k = 4: True
Time and Space Complexity
- Time Complexity: O(n), where n is the length of the array
- Space Complexity: O(1), as we only use constant extra space
Conclusion
The solution efficiently checks if the LCM of array elements is divisible by a given number by simply checking if any element is divisible by that number. This approach avoids the expensive computation of actual LCM values.
