C++ Implementation of Problem 6

View source code here on GitHub!

Includes

Solution

uint64_t p0006()
int main(int argc, char const *argv[])

Note

This function is only present in the Python test runner, or when compiling as a standalone program.

 1/*
 2Project Euler Problem 6
 3
 4I know there is a closed form solution to sum of squares, but I didn't want to
 5cheat and look it up. I was able to remember the closed form formula for sum of
 6natural numbers, though, so this is still pretty fast.
 7
 8Problem:
 9
10The sum of the squares of the first ten natural numbers is,
111**2 + 2**2 + ... + 10**2 = 385
12
13The square of the sum of the first ten natural numbers is,
14(1 + 2 + ... + 10)**2 = 55**2 = 3025
15
16Hence the difference between the sum of the squares of the first ten natural
17numbers and the square of the sum is 3025 − 385 = 2640.
18
19Find the difference between the sum of the squares of the first one hundred
20natural numbers and the square of the sum.
21*/
22#ifndef EULER_P0006
23#define EULER_P0006
24#include <stdint.h>
25#include <iostream>
26#include "include/macros.hpp"
27
28uint64_t EMSCRIPTEN_KEEPALIVE p0006() {
29    uint64_t sum = 100 * 101 / 2, sum_of_squares = 0;
30    for (uint64_t i = 1; i < 101; i++)
31        sum_of_squares += i * i;
32    return sum * sum - sum_of_squares;
33}
34
35PROGRAM_TAIL(p0006)
36#endif

Tags: arithmetic-progression, sequence-summation