patterncppMajor
Project Euler -problem 1
Viewed 0 times
problemprojecteuler
Problem
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?
https://projecteuler.net/problem=1
Is there any hack to do modulo operation in better way?
#include
int main()
{
unsigned int sum=0;
for( int i = 0; i < 1000; ++i )
{
if( ( i % 3 == 0 ) || ( i % 5 == 0 ) ||
( ( i % 3 == 0 ) && ( i % 5 == 0 ) ) )
{
sum += i;
}
}
std::cout<< sum <<"\n";
}Solution
This is not a hack.
What you have here is essentially:
The truth table for
\begin{array} {|cc|c|}
\hline
a & b & a \lor b \\
\hline
0 & 0 & 0\\
0 & 1 & 1\\
1 & 0 & 1\\
1 & 1 & 1\\
\hline
\end{array}
Where \$0\$ indicates
Therefore, the last part of your
is exactly the same as
So your
Arithmetic Sum
Project Euler 1 can be transformed into a Arithmetic sum problem.
Ask yourself these questions:
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.
if( ( i % 3 == 0 ) || ( i % 5 == 0 ) ||
( ( i % 3 == 0 ) && ( i % 5 == 0 ) ) )What you have here is essentially:
if( a || b || ( a && b ) )The truth table for
a || b is:\begin{array} {|cc|c|}
\hline
a & b & a \lor b \\
\hline
0 & 0 & 0\\
0 & 1 & 1\\
1 & 0 & 1\\
1 & 1 & 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 && 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.
Code Snippets
if( ( i % 3 == 0 ) || ( i % 5 == 0 ) ||
( ( i % 3 == 0 ) && ( i % 5 == 0 ) ) )if( a || b || ( a && b ) )if( a || b || ( a && b ) )if( a || b )if( ( i % 3 == 0 ) || ( i % 5 == 0 ) )Context
StackExchange Code Review Q#86126, answer score: 22
Revisions (0)
No revisions yet.