python数组查找元素
LCM is the lowest multiple of two or more numbers. Multiples of a number are those numbers which when divided by the number leave no remainder. When we are talking about the multiple, we consider only the positive number. For example, the LCM of 12 and 48 is 48 because 48 is 4th multiple of 12 and 48 is 1st multiple of 48. Here, an array of positive elements will be provided by the user and we have to find the LCM of the elements of the array by using the Python. To find LCM of the elements of the array, use the following algo,
LCM是两个或多个数字的最小倍数 。 数字的倍数是那些除以数字后没有余数的数字。 当我们谈论倍数时,我们只考虑正数。 例如,12和48的LCM是48,因为48是4 12 次倍数和48是48 1 个倍数。 在这里,用户将提供一个正元素数组,我们必须使用Python查找该数组元素的LCM 。 要查找数组元素的LCM ,请使用以下算法,
Algorithm to find the LCM of array elements
查找数组元素的LCM的算法
We need to import the math module to find the GCD of two numbers using math.gcd() function.
我们需要导入math模块以使用math.gcd()函数查找两个数字的GCD。
At first, find the LCM of initial two numbers using: LCM(a,b) = a*b/GCD(a,b). And, then find the LCM of three numbers with the help of LCM of first two numbers using LCM(ab,c) = lcm(lcm(a1, a2), a3). The same concept we have implemented.
首先,使用以下公式找到初始两个数字的LCM: LCM(a,b)= a * b / GCD(a,b) 。 然后,使用LCM(ab,c)= lcm(lcm(a1,a2),a3)在前两个数字的LCM的帮助下找到三个数字的LCM。 我们已经实现了相同的概念。
Now, we will write the Python program in a simple way by implementing the above algorithm.
现在,我们将通过实现上述算法以简单的方式编写Python程序。
Program:
程序:
# importing the module
import math
# function to calculate LCM
def LCMofArray(a):
lcm = a[0]
for i in range(1,len(a)):
lcm = lcm*a[i]//math.gcd(lcm, a[i])
return lcm
# array of integers
arr1 = [1,2,3]
arr2 = [2,3,4]
arr3 = [3,4,5]
arr4 = [2,4,6,8]
arr5 = [8,4,12,40,26,28]
print("LCM of arr1 elements:", LCMofArray(arr1))
print("LCM of arr2 elements:", LCMofArray(arr2))
print("LCM of arr3 elements:", LCMofArray(arr3))
print("LCM of arr4 elements:", LCMofArray(arr4))
print("LCM of arr5 elements:", LCMofArray(arr5))
Output
输出量
LCM of arr1 elements: 6
LCM of arr2 elements: 12
LCM of arr3 elements: 60
LCM of arr4 elements: 24
LCM of arr5 elements: 10920
翻译自: https://www.includehelp.com/python/find-the-lcm-of-the-array-elements.aspx
python数组查找元素