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

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

    You are overcomplicating things. You just need a list of numbers that are multiples of 3 or 5 which you can get easily with a list comprehension:

    >>> [i for i in range(1000) if i % 3 == 0 or i % 5 == 0]
    

    Then use sum to get the total:

    >>> sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
    <<< 233168
    

    Or even better use a generator expression instead:

    >>> sum(i for i in range(1000) if i % 3 == 0 or i % 5 == 0)
    

    Or even better better (courtesy Exelian):

    >>> sum(set(list(range(0, 1000, 3)) + list(range(0, 1000, 5))))
    
    0 讨论(0)
  • 2020-12-29 12:39

    here is my solution:

    for n in range(100):
        if n % 5==0:
            if n % 3==0:
            print n, "Multiple of both 3 and 5"    #if the number is a multiple of 5, is it a multiple of 3? if yes it has has both.
    
        elif n % 5==0:
            print n, "Multiple of 5"
    
        elif n % 3==0:
            print n, "Multiple of 3"
    
        else:
            print n  "No multiples"
    
    0 讨论(0)
  • 2020-12-29 12:43

    Here is the code:

    count = 1000
    m = [3, 5, 3*5]
    result = 0
    Sum = 0
    for j in m:
        result = 0
        for i in range(count):
            if i*j < 1000:
                result = result + i*j
            elif i == (count - 1):
                if j < 15:
                    Sum = result + Sum
                elif j == 15:
                    Sum = Sum - result
                    print(Sum)
    
    0 讨论(0)
  • 2020-12-29 12:44
    t = int(input())
    for a in range(t):
    n = int(input().strip())
    sum=0
    for i in range(0,n):
           if i%3==0 or i%5==0:
                sum=sum+i
    print(sum)
    
    0 讨论(0)
  • 2020-12-29 12:44

    You can also use functional programming tools (filter):

    def f(x):
        return x % 3 == 0 or x % 5 == 0
        filter(f, range(1,1000)) 
    print(x)
    

    Or use two lists with subtraction of multiples of 15 (which appears in both lists):

    sum1 = []
    for i in range(0,1000,3):
        sum1.append(i)
    sum2 = []
    for n in range(0,1000,5):
        sum2.append(n)
    del sum2[::3] #delete every 3-rd element in list
    print(sum((sum1)+(sum2)))
    

    I like this solution but I guess it needs some improvements...

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

    I know it was 7 years ago but I wanna share my solution to this problem.

    x= set()
    for i in range(1,1001):
        if (i % 3) == 0:
            x.add(i)
    
    for j in range(1,1001):
        if (j % 5) == 0:
            x.add(j)
    
    print(sum(x))
    
    0 讨论(0)
提交回复
热议问题