License Public Domain
Lines 51
Keywords
Euler28 (8)
Permissions
Owner: jsimones
Group Owner: SnortSnort
Viewable by Everyone
Editable by All Siafoo Users
Hide
Stay up to dateembedded code automagically updates, each snippet and article has a feed Join Siafoo Now or Learn More

Project Euler 28 Atom Feed 0

# 's
 1/*
2Number spiral diagonals
3Problem 28
4Starting with the number 1 and moving to the right in a clockwise direction a 5
5by 5 spiral is formed as follows:
6
721 22 23 24 25
820 7 8 9 10
919 6 1 2 11
1018 5 4 3 12
1117 16 15 14 13
12
13It can be verified that the sum of the numbers on the diagonals is 101.
14
15What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed
16in the same way?
17
18*/
19#include <iostream>
20#include <math.h>
21
22int spiral_diagonal_sum1 (int N)
23{// Step through each corner number in the NxN spiral pattern, using the fact
24 // that the side length of each concentric box grows by 2.
25 int term = 1;
26 int diagonal_sum = 1;
27 int step = 2;
28 int i = 1;
29
30 while (step <= N - 1) {
31 term += step;
32 diagonal_sum += term;
33 i += 1;
34 if (i > 4) {
35 step += 2;
36 i = 1;
37 }
38 }
39 return diagonal_sum;
40 }
41
42int spiral_diagonal_sum2 (int N)
43{// In a box of side length n, the number in the upper-right corner is n^2 and
44 // the other corners are n^2 minus 1-, 2-, and 3-times n-1 (thanks, Mike!).
45 int diagonal_sum = 1;
46
47 for (int n = 3; n <= N; n += 2) {
48 diagonal_sum += 4 * pow (n, 2) - 6 * n + 6;
49 }
50 return diagonal_sum;
51}
52
53int main ()
54{
55 int diagonal_sum;
56
57 diagonal_sum = spiral_diagonal_sum2 (1001);
58 std::cout << diagonal_sum << std::endl;
59 return 0;
60}