Project Euler -problem 1 Find the sum of all the multiples of 3 or 5 below 1000.


https://projecteuler.net/problem=1
Is there any hack to do modulo operation in better way?

#include&lt;iostream&gt;

int main()
{
    unsigned int sum=0;

    for( int i = 0; i &lt; 1000; ++i )
    {
        if( ( i % 3 == 0 ) || ( i % 5 == 0 )  ||
           ( ( i % 3 == 0 ) &amp;&amp; ( i % 5 == 0 ) ) )
        {
            sum += i;  
        }
    }
    std::cout&lt;&lt; sum &lt;&lt;"\n";                         
}
This is not a hack.

if( ( i % 3 == 0 ) || ( i % 5 == 0 )  ||
   ( ( i % 3 == 0 ) &amp;&amp; ( i % 5 == 0 ) ) )


What you have here is essentially:

if( a || b || ( a &amp;&amp; b ) )


The truth table for a || b is:

\begin{array} {|cc|c|}
\hline
a &amp; b &amp; a \lor b \\
\hline
0 &amp; 0 &amp; 0\\
0 &amp; 1 &amp; 1\\
1 &amp; 0 &amp; 1\\
1 &amp; 1 &amp; 1\\
\hline
\end{array}

Where \$0\$ indicates false and \$1\$ indicates true.

Therefore, the last part of your if is completely useless.

if( a || b || ( a &amp;&amp; b ) )


is exactly the same as

if( a || b )


So your if statement can be:

if( ( i % 3 == 0 ) || ( i % 5 == 0 ) )


Arithmetic Sum

Project Euler 1 can be transformed into a Arithmetic sum problem.

Ask yourself these questions:


How many numbers that are multiples by 3 are there below 1000 ?
How many numbers that are multiples by 5 are there below 1000 ?
How many numbers that are multiples by both 3 and 5 (i.e. 15) are there below 1000 ?


Then use the values for these individual arithmetic sums to arrive at your final answer. This will give your code a complexity of \$O(1)\$ instead of \$O(n)\$

As this is Project Euler, I only want to give you a little push in the right direction, hope this helps.