Multiples of 3 and 5
Problem 1
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.
Project Euler.net
Python Code
def sumMultiples():
sumTotal = 0
lwrBnd = 1
uprBnd = input("Enter the upper bound:")
uprBnd = uprBnd-1
print ("Enter the numbers sum of whose multiples are to be found:")
a = input("First Number:")
b = input("Second Number:")
lcm = 2
while lcm > 1:
if lcm%a == 0 and lcm%b == 0:
break
else:
lcm = lcm+1
lastTerm = a*(uprBnd/a)
n = lastTerm/a
sumTotal = sumTotal + a*(n*(n+1))/2
lastTerm = b*(uprBnd/b)
n = lastTerm/b
sumTotal = sumTotal + b*(n*(n+1))/2
lastTerm = lcm*(uprBnd/lcm)
n = lastTerm/lcm
sumTotal = sumTotal - lcm*(n*(n+1))/2
print "Required Sum is",sumTotal
sumMultiples()
Find the sum of all the multiples of 3 or 5 below 1000.
Project Euler.net
Python Code
def sumMultiples():
sumTotal = 0
lwrBnd = 1
uprBnd = input("Enter the upper bound:")
uprBnd = uprBnd-1
print ("Enter the numbers sum of whose multiples are to be found:")
a = input("First Number:")
b = input("Second Number:")
lcm = 2
while lcm > 1:
if lcm%a == 0 and lcm%b == 0:
break
else:
lcm = lcm+1
lastTerm = a*(uprBnd/a)
n = lastTerm/a
sumTotal = sumTotal + a*(n*(n+1))/2
lastTerm = b*(uprBnd/b)
n = lastTerm/b
sumTotal = sumTotal + b*(n*(n+1))/2
lastTerm = lcm*(uprBnd/lcm)
n = lastTerm/lcm
sumTotal = sumTotal - lcm*(n*(n+1))/2
print "Required Sum is",sumTotal
sumMultiples()
No comments:
Post a Comment