# How do you write a program to find magic numbers?

#include<stdio.h>

unsigned sum_row (unsigned* sq, const unsigned width, const unsigned row) {

unsigned sum, col;

sum = 0;

for (col=0; col<width; ++col)

sum += sq[row*width+col];

return sum;

}

unsigned sum_col (unsigned* sq, const unsigned width, const unsigned col) {

unsigned sum, row;

sum = 0;

for (row=0; row<width; ++row)

sum += sq[row*width+col];

return sum;

}

unsigned sum_diag (unsigned* sq, const unsigned width) {

unsigned sum, row, col;

sum = 0;

for (row=0, col=0; row<width; ++row, ++col)

sum += sq[row*width+col];

return sum;

}

unsigned sum_anti (unsigned* sq, const unsigned width) {

unsigned sum, row, col;

sum = 0;

for (row=0, col=width-1; row<width; ++row, --col)

sum += sq[row*width+col];

return sum;

}

bool is_magic (unsigned* sq, const unsigned width) {

unsigned magic, row, col;

magic = sum_row (sq, width, 0);

for (row=1; row<width; ++row)

if (magic!=sum_row(sq, width, row))

return false;

for (col=0; col<width; ++col)

if (magic!=sum_col(sq, width, col))

return false;

if (magic!=sum_diag(sq, width))

return false;

if (magic!=sum_anti(sq, width))

return false;

return true;

}

int main () {

const unsigned width = 3;

unsigned a[width][width] {{2,7,6},{9,5,1},{4,3,8}};

unsigned row, col;

printf ("Square:\n\n");

for (row=0; row<width; ++row) {

for (col=0; col<width; ++col) {

printf ("%d ", a[row][col]);

}

printf ("\n");

}

printf ("\n");

if (is_magic((unsigned*)&a, width))

printf ("The square is magic with a magic constant of %d\n", sum_row((unsigned*)&a, 3,0));

else

printf ("The square is not magic\n");

return 0;

}