HackerRank Project Puler #1
<p>What is wrong with this code? It is not passing case 2 &amp; 3 on HackerRank.</p>

<pre><code>T=long(input())
while T&gt;0:
    N=long(input())
    sum=0
    for i in range (1,N):
        if i%3==0 or i%5==0:
            sum+=i
    print (sum)
    T-=1
</code></pre>

<p>I'm new in programming and can't figure out what I did wrong.</p>

<p><a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler001" rel="nofollow">https://www.hackerrank.com/contests/projecteuler/challenges/euler001</a></p>

<p>There are couple of issues with the code. First since you're using <code>long</code> I guess you're running it on Python 2. On Python 2 <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow"><code>range</code></a> will generate a <code>list</code> and you'll run out of memory since problem description states that max <code>N</code> is <code>10^9</code>. You could fix that problem by switching to <a href="https://docs.python.org/2/library/functions.html#xrange" rel="nofollow"><code>xrange</code></a> that returns <a href="https://docs.python.org/2/library/stdtypes.html#typesseq-xrange" rel="nofollow">xrange object</a> instead.</p>

<p>If you make the change described above the second issue would be speed. Since max <code>N</code> is <code>10^5</code> you'd potentially have to iterate over <code>10^14</code> numbers which takes far too long. In order to fix the used algorithm needs to be changed. You can use formula <code>n * (n + 1) * mul / 2</code> to calculate the sum of all multiples of <code>mul</code> in range <code>0...n</code>. Then you solve a case by just adding the sum of multiples of <code>3</code> and <code>5</code> and subtract multiples of <code>15</code>:</p>

<pre><code>def sum_multiples(num, mul):
    n = num / mul
    return n * (n + 1) * mul / 2

for _ in xrange(int(raw_input())):
    num = int(raw_input()) - 1
    print sum_multiples(num, 3) + sum_multiples(num, 5) - sum_multiples(num, 15)
</code></pre>

python