**Stay up to date**– embedded code automagically updates, each snippet and article has a feed Join Siafoo Now or Learn More

# Euler28, C++, Analytical Solution 0

Language | C++ |

# 's

` 1/*********************************************************************`

2 Number spiral diagonals

3 Problem 28

4 Starting with the number 1 and moving to the right in a clockwise

5direction a 5 by 5 spiral is formed as follows:

6

7 21 22 23 24 25

8 20 7 8 9 10

9 19 6 1 2 11

10 18 5 4 3 12

11 17 16 15 14 13

12

13 It can be verified that the sum of the numbers on the diagonals is 101.

14

15 What is the sum of the numbers on the diagonals in a 1001 by 1001

16spiral formed in the same way?

17*********************************************************************/

18

19/*********************************************************************

20 We begin by noticing immediately that the top right entry is always

21 n^2, where n is the length of the spiral. The top left entry must

22 therefore be (n-1) less than the top right, since there are n numbers

23 per side. This pattern is repeated in a counterclockwise direction

24 around the square. We summarize below:

25

26 top right: n^2

27 top left: n^2 - (n-1) = n^2- n+1

28 bottom left: n^2 -2(n-1) = n^2-2n+2

29 bottom right: n^2 -3(n-1) = n^2-3n+3

30

31 Summing up these diagonals yields: 4n^2 - 6n + 6

32 Therefore, we simply sum all the odd polynomials from n=3->1001

33*********************************************************************/

34#include <iostream>

35

36using namespace std;

37

38int main()

39{

40 const int max_n = 1001;

41

42 // Start at n = 3, and add in 1 (for n = 1 central 'square')

43 int sum = 1;

44

45 for (int n = 3; n <= max_n; n+=2)

46 sum += 4*n*n - 6*n + 6;

47

48 cout << sum << endl;

49}

50

51// >: 669171001

Add a Comment