The sum of the squares of the first ten natural numbers is:
\1ドル^2 + 2^2 + ... + 10^2 = 385\$
The square of the sum of the first ten natural numbers is:
\$(1 + 2 + ... + 10)^2 = 55^2 = 3025\$
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is \3025ドル − 385 = 2640\$.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
//Project euler problem 6
#include <iostream>
#include <cmath>
using namespace std;
unsigned int sum(int);
unsigned int sqsum(int);
int main()
{
cout << sum(100)*sum(100) - sqsum(100);
}
unsigned int sum(int n) // function for finding sum of n numbers
{
return (n*(n+1))/2;
}
unsigned int sqsum(int n) // function for finding sum of squares
{
return ((n)*(n+1)*(2*n +1 ))/6 ;
}
1 Answer 1
Here are a few comments that may help you improve your code.
Use only necessary #include
s
The #include <cmath>
line is not necessary and can be safely removed.
Avoid "magic numbers"
Since the constant 100 is used several times within the code, it makes sense to create a constant instead. This also helps with troubleshooting since you can quickly change it to small values (e.g. 10) for which you already know the answer:
const int maxnum = 100;
Avoid abusing using namespace std
Don't abuse using namespace std
Especially in a very simple program like this, there's little reason to use that line. Putting using namespace std
at the top of every program is a bad habit that you'd do well to avoid.
Eliminate function prototypes by ordering
If you put the sum
and sqsum
implementations above main
in the source code, you don't need the function prototypes.
End the last console output with a newline
The output to the program is a little neater on most machines if you output a newline character after the last of the program's console output.
Avoid unnecessary function calls
It doesn't make a huge difference in this code, but the code dosn't need to make two calls to sum()
. Instead, the main
routine might look like this:
int main()
{
const int maxnum = 100;
unsigned square_of_sum = sum(maxnum);
square_of_sum *= square_of_sum;
std::cout << square_of_sum - sqsum(maxnum)-a << '\n';
}
-
\$\begingroup\$
sumofsquares
stands first for sum and then square of the sum; despite its name, never for sum of the squares. Valid identifierssum
,square_of_the_sum
are available. If you are feeling terses
(for sum) ands2
(for square of sum) are also acceptable. \$\endgroup\$abuzittin gillifirca– abuzittin gillifirca2015年01月08日 14:32:41 +00:00Commented Jan 8, 2015 at 14:32 -
\$\begingroup\$ @abuzittingillifirca: Good point, thanks! I've updated my answer to include your suggestion. \$\endgroup\$Edward– Edward2015年01月08日 14:37:54 +00:00Commented Jan 8, 2015 at 14:37
sqsum
is not correct. How many times does the loop execute? What is the initial value ofsum
? \$\endgroup\$