python数组查找元素_Python程序查找数组元素的LCM

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 倍数和4848 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数组查找元素

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值