Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiples of 3 and 5
#1
I was attempting to solve a problem on this site

Quote: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 attempt:
answer = 0
for num in (range(1, 1000)):
    if ((num % 3 == 0) or (num % 5 == 0)):
        print(num)
        answer += num

print("Answer is " + str(answer))
I googled, and found the same logic on the Wikipedia page. They give a more complex solution for larger numbers. I'm unable to understand how to implement that complex formula in Python. For learning purposes, how would you implement it? My problem is more math related than programming related.
Reply
#2
Do you not understand sigma notation? (sigma is that big weird e-looking thing.) It's just math for loops. Call what is under the sigma start, call what is under the sigma end, and define a function called f for what is to the right of the sigma. The sigma is equivalent to:

total = 0
for i in range(start, end + 1):
    total += f(i)
So the first sigma is the same as:

total = 0
for i in range(1, int((n - 1) / k) + 1):
   total += k * i
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I want to create small multiples grouped bar plot, and facing some aesthetics issuess dev_kaur 0 2,052 Dec-05-2020, 08:49 AM
Last Post: dev_kaur
  Read Multiples Text Files get specific lines based criteria zinho 5 4,157 May-19-2020, 12:30 PM
Last Post: zinho
  how to make a program with a certain number of multiples? syafiq14 3 3,597 Jan-01-2020, 02:39 PM
Last Post: syafiq14
  How to remove multiples in a list jasper100125 6 4,446 Aug-20-2019, 06:38 AM
Last Post: buran
  input multiples images into specific cells with data IONSASOON 1 3,564 Mar-13-2017, 04:09 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020