Finding the LCM of a range of numbers

前端 未结 14 885
时光说笑
时光说笑 2020-12-08 05:03

I read an interesting DailyWTF post today, \"Out of All The Possible Answers...\" and it interested me enough to dig up the original forum post where it was submitted. This

14条回答
  •  再見小時候
    2020-12-08 05:39

    Here's my Python stab at it:

    #!/usr/bin/env python
    
    from operator import mul
    
    def factor(n):
        factors = {}
        i = 2 
        while i <= n and n != 1:
            while n % i == 0:
                try:
                    factors[i] += 1
                except KeyError:
                    factors[i] = 1
                n = n / i
            i += 1
        return factors
    
    base = {}
    for i in range(2, 2000):
        for f, n in factor(i).items():
            try:
                base[f] = max(base[f], n)
            except KeyError:
                base[f] = n
    
    print reduce(mul, [f**n for f, n in base.items()], 1)
    

    Step one gets the prime factors of a number. Step two builds a hash table of the maximum number of times each factor was seen, then multiplies them all together.

提交回复
热议问题