Monday 29 December 2014

Multiples of 3 and 5 and their sum


Question: Find the multiples of 3 and 5 and add them till the numbers below 1000. For example if you consider numbers below 10 you will have [3.5,6,9] as the numbers which are divisible by 3 and 5. Their sum will be 23(3+5+6+9), where 23 is the required answer for numbers below 10(<10). Similarly if we consider numbers below 20 you will have [3,6,5,9,10,12,15,18] as the numbers which are divisible by either 3 or 5. Their sum will be 78(3+6+5+9+10+12+15+18) which will be the required answer for numbers below 20.
Similarly find out the sum for the numbers below 1000?

Answer: I have solved this question in two ways, first one I have answered this question using functions and in the second method which doesn't use functions. I have commented the code so that everyone will understand it perfectly. Please do tell me if you don't understand. I will for sure make it clear for you.

Approach using Functions:

#Defining a function as the code may be used any number of times.
#Step1:Defining the name of function
def sum_multiple(n):
#Initialize a variable sum1 = 0
    sum1 = 0
#Use the for loop to loop n-1 times
    for number in range(1,n):
#Make decision if the number is divisible by 3 or 5. Using 'OR' operator
        if number % 3 == 0 or number % 5 == 0:
#If condition is true add the value
            sum1 += number
#Finally print the sum.
    print sum1

#Use the function call for first 9 numbers.
sum_multiple(10) #Expected value of 23

#Use it to give the value for first 999 numbers(numbers below 1000).
sum_multiple(1000) #Value is 233168
Output:

23
233168

Normal Approach:

#Initialize a variable sum1 = 0
sum1 = 0
#Use the for loop to loop 999 times
for number in range(1,1000):
#Make decision if the number is divisible by 3 or 5. Using 'OR' operator
    if number % 3 == 0 or number % 5 == 0:
#If condition is true add the value
        sum1 += number
#Finally print the sum.
print sum1
Output:
233168

Note:This problem was found on Project Euler

No comments:

Post a Comment