Time effciency for test case in euler #1 <p>Often times when solving questions on hackerrank codechef my code times out for certain test cases. I know it's because my code isn't efficient enough and I need to reduce the time complexity of the code. </p> <p>In this particular problem <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler001/submissions/code/3629090" rel="nofollow">Project Euler Multiples of 3 and 5</a> I don't seem to understand how the test cases timed out. If I'm not wrong code runs in O(n^2), that too considering the loop for taking the test cases. How can I make my code efficient?</p> <p>The description of the question is in the link. </p> <pre><code>#include &lt;cmath&gt; #include &lt;cstdio&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t, n; int n1,n2; int mul3, mul5, sum=0,sum3=0,sum5=0; cin&gt;&gt; t; while(t--){ cin&gt;&gt;n; sum=0; sum5=0; sum3=0; if(n%3==0) n1=n/3-1; else n1=n/3; if(n%5==0) n2=n/5-1; else n2=n/5; for(int i=0;i&lt;=n1;i++){ if(i&lt;=n2){ mul5= i*5; sum5+=mul5; } mul3=i*3; if((mul3%5)!=0) sum3+=mul3; sum = sum3+sum5; } cout &lt;&lt; sum &lt;&lt; endl; } system("PAUSE"); return 0; } </code></pre>