RSS Feed

MATH & PYTHON

0

May 15, 2023 by zehra kaya

4 February 2022

Problem

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.

Solution

multiples = [x for x in range(1,1000) if x%3 == 0]
for x in range(1,1000):
	if (x % 5 == 0 and x%3 != 0):
		multiples.append(x)
total = 0
for i in multiples:
	total += i
print(total)

sum(multiples)
multiples = [x for x in range(1,1000) if x%3 == 0]
total = [y for y in range(1,1000) if (y % 5 == 0 and y %3 != 0)]
multiples.extend(total)
sum(multiples)

SO, WHY HOW?

multiples = [x for x in range(1,1000) if x%3 == 0]

this means:

multiples = [ ]
for x in range(1,1000): 
  if x % 3 == 0:  
    multiples.append(x)
multiples = [ ] 
  • Firstly, with this equality the “multiples” that is a empty list is created so that we can put the natural numbers below 1000 that are multiples of 3 in the list
for x in range(1,1000): 
  if x % 3 == 0:  
    multiples.append(x)     
  • Then every number x below 1000 that is divisible by 3 are appended to the list called “multiples”
for x in range(1,1000):             
	if (x % 5 == 0 and x%3 != 0):
		multiples.append(x) 
  • With this code, every number x below 1000 that is indivisible by 3 and divisible by 5 appended to the list called “multiples“.
total = 0         
  • The “total” number that will change with the for loop is created .
for i in multiples: 
	total += i  
  • Every i element are added to the total value then this total value changes as the adding new element in the list. For instance,
    • First, total = 0 this goes into the list,
    • Then, add up with the first element in the list
    • And add up every single element in the list until every numbers are added to the total value.
    • In this way, we can find the sum of all the multiples of 3 or 5 below 1000.
sum(multiples)
  • Part 4 and 5 may seem a little bit long , so on the other hand, this code sum(multiples) had better use instead of using long one.
multiples = [x for x in range(1,1000) if x%3 == 0]
total = [y for y in range(1,1000) if (y % 5 == 0 and y %3 != 0)]
multiples.extend(total)
sum(multiples)

Generalized Problem

Find the sum of all the multiples of b or c below a .

Generalized Solution

def solution():
  a = input(int())
  b = input(int())
  c = input(int())
  multiples = [x for x in range(1,int(a)) if (x % (int(c))) == 0]
  total = [y for y in range(1,int(a)) if (y % (int(b)) == 0 and (y % (int(c))) != 0)]
  multiples.extend(total)
  print(sum(multiples))
 
  
solution()
  • a function called “solution()” is defined by def command to be able to make it short and to use it quicker whenever you need it.
  • add “input(int())” for each variables

it’s done! 🙂

hope it’s clear.


0 comments »

Leave a Reply

Your email address will not be published. Required fields are marked *