I am just starting to try my hands in the problems of Project Euler and i have got stuck in the first code itself. Can someone please tell me in the below code where i am going wrong.
The problem statement is as follows:
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.
And my solution is as follows:
multiple1 = 5 multiple2 = 3 index = 2 sum = 0 while multiple1 < 1000 or multiple2 < 1000: if multiple1 < 1000: sum = sum + multiple1 multiple1 = 5 * index if multiple2 < 1000: sum = sum + multiple2 multiple2 = 3 * index index = index + 1 print (sum)
I know someone has already posted the solution somewhere, but i just want to figure out where i am going wrong with the logic.
Your code will generate duplicate values. For example, 15 is multiple of both 3 and 5. Hence, you are adding duplicate values to the sum every time a number is multiple of both 3 and 5. The code below fixes your issue.
multiple1 = 5 multiple2 = 3 index = 1 sum = 0 while multiple1 < 1000 or multiple2 < 1000: multiple1 = 5 * index multiple2 = 3 * index if (multiple1 < 1000) and (multiple1 % 3 != 0): sum = sum + multiple1 if (multiple2 < 1000): sum = sum + multiple2 index = index + 1 print (sum)
The simplest way to do this
total = 0 for i in range(1,1000): if i%3 == 0 or i % 5 == 0: total += i print(total)
you can do without loop also
n=1000 remider=(n+2)//3 #get the reminder of 3 remider2=(n+4)//5 #get the reminder of 5 fsum = 3*((remider-1)*(remider))/2 #3*(N*(N+1)/2)) ssum = 5*((remider2*(remider2-1))/2) #5*(N*(N+1)/2)) first_list = list(range(3,3*(remider),3)) #list of mutiple of 3 second_list = list(range(5,5*(remider2),5)) #list of mutiple of 5 c_sum=sum(list(set(second_list) & set(first_list))) # sum of common elements print(fsum+ssum-c_sum)