【问题标题】:finding the least common multiple寻找最小公倍数
【发布时间】:2021-07-16 20:04:10
【问题描述】:
a = int(input(''))
b = int(input(''))
g = 0


def fac(n):
    if n <= a:
        return a
    else:
        return n * fac(n - 1)


numbers = []
i = a
while a <= i <= b:
    if a <= i <= b:
        numbers.append(i)
        i += 1
    else:
        break

for k in range(b, fac(b)):
    for l in numbers:
        if k % l == 0:
            g = k

print(g)

我正在编写一个代码来计算范围内数字的最小公倍数。我检查了 fac 函数和 while(if,else) 我认为 for 部分有问题。我找不到错误的部分。

【问题讨论】:

  • 可以添加输出吗?

标签: python loops for-loop numbers


【解决方案1】:

我正在编写一个代码来计算范围内数字的最小公倍数。我检查了 fac 函数和 while(if,else) 我认为 for 部分有问题。我找不到错误的部分。

恐怕我不得不说错误的部分是整个程序,因为我不认为factorial函数对这个问题有用,而for部分没有没有任何意义,至少对我来说。这是我在一个范围内查找所有数字的least common multiple 的建议。为了节省一些时间,它首先确定可能的质因数集,然后将其用于数字的质因数分解,最后用于计算 lcm。

a = int(input())
b = int(input())
# collect possible prime factors of numbers up to b
h = 2        # highest prime so far
primes = [h] # list to store primes
n = 3        # next number to check
while n*h <= b:
    for p in primes:
        if p*p > n:
            h = n            # new prime
            primes.append(h) # enlist it
            break
        if not n%p: break
    n += 2
# prime factorization of all numbers in range a to b
factors = []
for n in range(a, b+1): # range() wants end+1
    factor = {}
    for p in primes:
        while not n%p:  # divisible: count p as factor
            factor[p] = factor.get(p, 0) + 1
            n //= p
        if (n == 1): break
    else: factor[n] = 1
    factors.append(factor)
# reduce the b-a+1 factorizations to one common
factor = {}
for f in factors:
    factor = {k: max(factor.get(k, 0), f.get(k, 0)) for k in factor|f.keys()}
# produce the lcm from the common factors
lcm = 1
for p, e in factor.items(): lcm *= p**e
print(lcm)

【讨论】:

    【解决方案2】:

    我无法理解你找到最小公倍数的逻辑,但你可以这样做:

    a = int(input(''))
    b = int(input(''))
    g = 0
    
    
    if a > b:  
        g = a  
    else:  
        g = b  
    while(True):  
        if((g % a == 0) and (g % b == 0)):   
            break  
        g += 1 
    
    print(g)
    
    

    【讨论】:

    • 我必须找到具有多个数字的最小公倍数,例如,如果 a 是 9,b 是 13,我必须找到 9,10,11,12,13 的公倍数,所以我使 fac 函数决定范围(将范围内的所有值相乘将是最大值)并将 a,b 之间的数字添加到列表数字中
    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2020-10-12
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    相关资源
    最近更新 更多