A spiral diagonal is formed when you take a number, 1
, and increase that number as you move to the right and below. This forms a spiral.
The following slides show how a number spiral is formed for a 4x4 matrix.
The sum of the diagonals in a 3x3 number spiral is .
In the number spirals diagonal problem, the sum of diagonals for nxn needs to be found.
If one looks closely, one can find a pattern. Consider the following matrix.
The values in each diagonal correspond to:
These correspond to the following sequence:
The sum of all the terms includes the one in the center; therefore, it becomes:
Sum(n) =
Sum(n) =
Sum(n) =
Using summation rules we can reduce it to:
Sum(n) =
This simple formula can then be used to calculate the sum of the diagonal for the matrix of any dimension.
Remember: Here,
n
equals 1/2 the number of elements in a diagonal, excluding the center term.
n =
Wheredim
is the dimension of the matrix.
The following code shows how to find the sum of the diagonal in a number spiral for an nxn matrix.
#include <iostream>using namespace std;// declare function sumint sum(int dim){int n = (dim - 1) /2;//find n// use the formula defined aboveint x = (3 + 2 * n * ( 8 * n * n + 15 * n +13)) /3;return x;}int main() {// call the function and print the valueint diagonal = sum(5);cout << diagonal << endl;return 0;}
Free Resources