Magic squares of doubly even order: Difference between revisions

Content added Content deleted
(Added solution for D)
(Added C implementation.)
Line 392: Line 392:
|}
|}


=={{header|C}}==
Takes number of rows from command line, prints out usage on incorrect invocation.
<lang C>
/*Abhishek Ghosh, 15th November 2017*/

#include<stdlib.h>
#include<ctype.h>
#include<stdio.h>

int** doublyEvenMagicSquare(int n) {
if (n < 4 || n % 4 != 0)
return NULL;

int bits = 38505;
int size = n * n;
int mult = n / 4,i,r,c,bitPos;

int** result = (int**)malloc(n*sizeof(int*));
for(i=0;i<n;i++)
result[i] = (int*)malloc(n*sizeof(int));

for (r = 0, i = 0; r < n; r++) {
for (c = 0; c < n; c++, i++) {
bitPos = c / mult + (r / mult) * 4;
result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
}
}
return result;
}

int numDigits(int n){
int count = 1;
while(n>=10){
n /= 10;
count++;
}
return count;
}

void printMagicSquare(int** square,int rows){
int i,j,baseWidth = numDigits(rows*rows) + 3;
printf("Doubly Magic Square of Order : %d and Magic Constant : %d\n\n",rows,(rows * rows + 1) * rows / 2);
for(i=0;i<rows;i++){
for(j=0;j<rows;j++){
printf("%*s%d",baseWidth - numDigits(square[i][j]),"",square[i][j]);
}
printf("\n");
}
}

int main(int argC,char* argV[])
{
int n;
if(argC!=2||isdigit(argV[1][0])==0)
printf("Usage : %s <integer specifying rows in magic square>",argV[0]);
else{
n = atoi(argV[1]);
printMagicSquare(doublyEvenMagicSquare(n),n);
}
return 0;
}
</lang>
Invocation and Output :
<pre>
C:\rosettaCode>doublyEvenMagicSquare 12
Doubly Magic Square of Order : 12 and Magic Constant : 870

1 2 3 141 140 139 138 137 136 10 11 12
13 14 15 129 128 127 126 125 124 22 23 24
25 26 27 117 116 115 114 113 112 34 35 36
108 107 106 40 41 42 43 44 45 99 98 97
96 95 94 52 53 54 55 56 57 87 86 85
84 83 82 64 65 66 67 68 69 75 74 73
72 71 70 76 77 78 79 80 81 63 62 61
60 59 58 88 89 90 91 92 93 51 50 49
48 47 46 100 101 102 103 104 105 39 38 37
109 110 111 33 32 31 30 29 28 118 119 120
121 122 123 21 20 19 18 17 16 130 131 132
133 134 135 9 8 7 6 5 4 142 143 144
</pre>
=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<lang cpp>#include <iostream>