A Multiples question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Avatar19
    New Member
    • Apr 2010
    • 43

    A Multiples question

    I am a bit confused because i believe I am answering this correctly. This is the question:
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
    Find the sum of all the multiples of 3 or 5 below 1000.
    My code is as follows

    Code:
    def mult(X):
        List = []
        k =1
        while X*k <1000:
            List.append(X*k)
            k+=1
        print List
        print sum(List[:])
    mult(3)
    mult(5)
    print 99500+166833
    I just put in some print checks to make sure I am not going crazy, this in my understanding accomplishes the question outputting the sum of all multiples of 3 and 5 below 1000 as "266333"
    Could someone just tell me if I am making a very stupid mistake in understanding this?
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Avatar19,

    The modulo operator is IDEAL for this problem.

    This is completely untested and is not a complete solution:
    Code:
    [i for i in range(1000) if not i%3 or not i%5]

    Comment

    • Avatar19
      New Member
      • Apr 2010
      • 43

      #3
      I got this:

      Code:
      sum([i for i in range(1000) if i % 3 == 0 or i % 5 == 0])
      which seems to do it very neatly
      Thanks

      Comment

      Working...