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

后端 未结 18 1005
萌比男神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:53

    I like this the most:

    def divisibles(below, *divisors):
        return (n for n in xrange(below) if 0 in (n % d for d in divisors))
    
    print sum(divisibles(1000, 3, 5))
    
    0 讨论(0)
  • 2020-12-29 12:54

    range(k,max) does not include max, so you're really checking up to and including 998 (while 999 is a multiple of 3). Use range(1,1000) instead.

    0 讨论(0)
  • 2020-12-29 12:54

    I know this was 3 months ago but as an experiment because I am new to python I decided to try and combine some of the other people answers and I came up with a method you can pass the max number to and the divisors as a list and it returns the sum:

    def sum_of_divisors(below, divisors):
        return sum((n for n in xrange(below) if 0 in (n % d for d in divisors)))
    
    max = 1000
    nums = [3, 5]
    
    print sum_of_divisors(max, nums)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-29 12:57

    I had to do it in range 1 , 100

    This is how I did it.

    For i in range(1,100):
    
    If i ÷ 3 == 0 and i ÷ 5 == 0:
    
     print(i) 
    

    So with 1000 you just change the 100 to 1000

    I had to find the multiples of 3 and 5 within 100 so if you need 3 or 5 just change it to or and it will give you more answers too. I'm just starting to learn so correct me if I'm wrong

    0 讨论(0)
  • 2020-12-29 12:59
    max = 1000  # notice this here
    result = 0
    for i in range(0,max):
    if i%3 == 0 or i%5 == 0:
        result += i
    
    print result
    

    This works, but use 1000 for max, so it includes 999 too.

    0 讨论(0)
提交回复
热议问题