HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Project Euler Problem #6 - sum square difference

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
problemsumdifferenceprojecteulersquare

Problem

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 
#include 
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 ;
}

Solution

Here are a few comments that may help you improve your code.

Use only necessary #includes

The #include 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';
}

Code Snippets

const int maxnum = 100;
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';
}

Context

StackExchange Code Review Q#75700, answer score: 6

Revisions (0)

No revisions yet.