# Project Euler #1: Multiples of 3 and 5

# Project Euler #1: Multiples of 3 and 5

+ 75 comments For anyone who is using Python3. If you've already converted from the iterive to the O(1) solution but you're still getting the "wrong answer" with Test Cases 2 and 3 here is why:

When you divide integers in python 3, the answer is converted automatically to a float. Becuase Test Cases 2 and 3 involve very large numbers, when you convert back to integer, there will be a huge rounding error and your answers will be wrong.

This is the issue I had to resolve. Luckily for me, my only division was a divide by two so I converted it to a bitwise right-shift.

+ 23 comments O(1) Solution : say N= 100 so, max multiple of 3 here below N is 99 i.e. 3*33 so, sum of all multiples of 3 has a pattern 3(1+2+3+....+33) use this

Here is the code in C++

`long N,num,three,five,fifteen=0; cin>>N; for(int i=0;i<N;i++) { cin>>num; //int sum=0; three=(num-1)/3; five=(num-1)/5; fifteen=(num-1)/15; cout << 3*(three*(three+1)/2)+5*(five*(five+1)/2)-15*(fifteen*(fifteen+1)/2)<<endl; } return 0;`

[deleted] + 0 comments The first challenge and I'm already wishing I'd paid more attention in math class.

+ 3 comments Here's how I approached the problem.( I used Java ) First I scanned akk the numbers and checked using modulus. This gave me a time out error. Then I used the sum of arithmatic progression formula, which got past the tine out error , but gave me a wrong answer error. This was because, the sums generated in test case 3 and 4 results were out of range of the long number's range. So, I used the BigInteger for sums and long for inputs. And finally the solution worked.

+ 2 comments If you get an timeout in case 2 and 3, stop iterating and checking with modulo. You need to calculate it, otherwise it's too slow.

Sort 971 Discussions, By:

Please Login in order to post a comment