EDIT (18/01/2013)

I have edited this post on the above date. However, the only change that I have made is that I am now hosting the source code (found at the end of this post) on GitHub. This means, that if I need to make a change to the code, I do not have to edit this post again – as it will pull the latest version of it from the relevant page on GitHub whenever it is accessed by a reader.


Reading a comment on my most recent post, I felt that I could optimise my code for Project Euler’s Problem Six. So, I went away and read up on the information provided by Kristan (in the comments section), and decided that I’d give it a go… in C.

There were a few reasons for switching to C, the biggest was that I only have a C compiler installed on this machine (a minimal install of MingW), another being that I’m a little more informed about the optimisation options (which I didn’t use for this project) that gcc provides.

Anyway, on with the code.


This is a solution to problem 6 on Project Euler. I’ve not posted it up here to gloat, or to provide answers for cheats. I’ve posted it, so that you can see how I solve this kind of problem.

The original problem reads like this:

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 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.

The Algorithm

Based on my code from the previous version of this project, and the knowledge provided by Kristan and The Internet at large, I’ve used a slightly different algorithm this time around. I’ve covered the algorithm in the comments section for my code, though. So, I guess you should just scroll down and read that.

I’m not a massive fan of providing information twice, in the same format. That and redundancy. That and redundancy

The Code

I’m not going to spend time explaining the code, since it contains enough information in the comments (within the code itself) and in the description of the algorithm above.

So, without further ado, here is the finished code:

By the way, I compiled this code with the following command:

gcc “Problem_Six_In_C.c” -o “Problem_Six_In_C.exe” -Wall

A simple problem with an extremely simple, now optimised,  solution.

Here’s a link to the c file: LINK

Until next time,


Related Post


Jamie is a .NET developer specialising in ASP.NET MVC websites and services, with a background in WinForms and Games Development. When not programming using .NET, he is either learning about .NET Core (and usually building something cross platform with it), speaking Japanese to anyone who'll listen, learning about languages, writing for this blog, or writing for a blog about Retro Gaming (which he runs with his brother)