Categories
Uncategorized

Multiples of 3 and 5 – Python

My very first Python script

Problem 1 from the Project Euler website.

The 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

My Solution

So let’s try it for all the numbers from 1 to 9

We get all the multiples of 3


# First, we declare variables
counter=1
ans=0

# then a list so we can put them all there
ansList=[]

# and finally the loop
while ans < 10:
	ansList.append(ans)
	ans=counter*3
	counter=counter+1
print ansList,

and that returns

[0 3 6 9]

Cool, it works!

Now we turn it into a function so we can use it with multiples of 3 and 5

def mults(mul,limit):
	counter=1
	ans=0
	ansList=[]
	while ans < limit:
		ansList.append(ans)
		ans=counter*mul
		counter=counter+1
	print ansList,

# and we call it with
mults(3,10)
mults(5,10)

which returns

[0, 3, 6, 9] [0, 5]

Which is nice, but we need to put them all in one list, so we change it to


ansList=[]    # We now make the list global...

def mults(mul,limit):
	counter=1
	ans=0
	while ans < limit:
		ansList.append(ans)
		ans=counter*mul
		counter=counter+1

mults(3,10)
mults(5,10)

print ansList    # ...and print it at the very end.

Which returns

[0, 3, 6, 9, 0, 5]

Now we need to get rid of duplicates and add them all up.


ansList=[]

def mults(mul,limit):
	counter=1
	ans=0
	while ans < limit:
		ansList.append(ans)
		ans=counter*mul
		counter=counter+1

mults(3,10)
mults(5,10)

# we remove the duplicates
remDup=list(set(ansList))

# then we add it all up
finalAns=sum(remDup)

# and print results
print finalAns

And that returns

23

Which is correct, so now we only need to change the ‘limit’ variables to…

mults(3,1000)
mults(5,1000)

…and we’ve solved the problem!!!!

Here’s a nicer way of writing it

ansList=[]
def mults(mul,limit):
	counter,ans=1,0
	while ans &lt; limit:
		ansList.append(ans)
		ans=counter*mul
		counter=counter+1
mults(3,1000)
mults(5,1000)
print sum(list(set(ansList)))

I am a massive eejit.

Here’s a better way of doing it.
the % operator will tell you if there is a remainder.
No need for a list, since the answer=answer+counter will add each number one by one.

counter=0
answer=0
while counter < 1000:
	if counter % 3 == 0 or counter % 5 == 0:
		answer=answer+counter
	counter=counter+1
print answer

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s