How to find the sum of all the multiples of 3 or 5 below 1000 in Python?

后端 未结 18 1140
萌比男神i
萌比男神i 2020-12-29 12:10

Not sure if I should\'ve posted this on math.stackexchange instead, but it includes more programming so I posted it here.

The question seems really simple, but I\'ve

18条回答
  •  不思量自难忘°
    2020-12-29 12:57

    I know this is from 6 years ago but I just thought id share a solution that found from a math formula that I thought was interesting as it removes the need to loop through all the numbers.

    https://math.stackexchange.com/a/9305

    def sum_of_two_multiples(nums, maxN):
        "takes tuple returns multiples under maxN (max number - 1)"
        n1, n2 = nums = nums[:2]
        maxN -= 1
        def k(maxN, kx):
            n = int(maxN / kx)
            return int(kx * (0.5 * n * (n+1)))
    
    return sum([k(maxN, n) for n in nums]) - k(maxN, n1*n2)
    

    Outputs the follows

    print(sum_of_two_multiples((3,5), 10))
    # 23
    print(sum_of_two_multiples((3,5), 1000))
    # 233168
    print(sum_of_two_multiples((3,5), 10**12))
    # 233333333333166658682880
    

提交回复
热议问题