How to resolve the algorithm Magic squares of singly even order step by step in the C programming language

Published on 7 June 2024 03:52 AM
#C

How to resolve the algorithm Magic squares of singly even order step by step in the C programming language

Table of Contents

Problem Statement

A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.

Create a magic square of 6 x 6.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Magic squares of singly even order step by step in the C programming language

This C program generates singly even magic squares for a given odd number of rows and columns n, where n ≥ 6, and (n - 2) % 4 == 0. Magic squares are square grids filled with distinct positive numbers, where the sum of each row, column, and main diagonal is the same.

  • oddMagicSquare Function:

    • Creates an odd-order magic square of size n × n using De La Loubère's algorithm.
    • It iteratively fills the square starting from the cell (0, n/2) and moving based on specific rules to ensure the magic properties.
    • The result is returned as a dynamically allocated 2D array.
  • singlyEvenMagicSquare Function:

    • Generates a singly even magic square using four odd-order magic squares (subGrids) of size n/2 × n/2.
    • It divides the n × n square into four n/2 × n/2 subgrids and fills them with the odd-order magic squares.
    • The values in each subgrid are adjusted based on their position to form a singly even magic square.
    • The result is returned as a 2D array.
  • numDigits Function:

    • Calculates the number of digits in a given integer n.
  • printMagicSquare Function:

    • Prints the magic square neatly, ensuring that all numbers have the same width (determined by the number of rows).
    • It also prints the magic constant, which is the sum of each row, column, and main diagonal.
  • main Function:

    • Checks if a valid integer n is provided as an argument.
    • Calls singlyEvenMagicSquare to generate the magic square and printMagicSquare to display it.

Source code in the c programming language

   #include<stdlib.h>
   #include<ctype.h>
   #include<stdio.h>
   
   int** oddMagicSquare(int n) {
        if (n < 3 || n % 2 == 0)
            return NULL;
 
        int value = 0;
        int squareSize = n * n;
        int c = n / 2, r = 0,i;
 
        int** result = (int**)malloc(n*sizeof(int*));
		
		for(i=0;i<n;i++)
			result[i] = (int*)malloc(n*sizeof(int));
 
        while (++value <= squareSize) {
            result[r][c] = value;
            if (r == 0) {
                if (c == n - 1) {
                    r++;
                } else {
                    r = n - 1;
                    c++;
                }
            } else if (c == n - 1) {
                r--;
                c = 0;
            } else if (result[r - 1][c + 1] == 0) {
                r--;
                c++;
            } else {
                r++;
            }
        }
        return result;
    }
 
    int** singlyEvenMagicSquare(int n) {
        if (n < 6 || (n - 2) % 4 != 0)
            return NULL;
 
        int size = n * n;
        int halfN = n / 2;
        int subGridSize = size / 4, i;
 
        int** subGrid = oddMagicSquare(halfN);
        int gridFactors[] = {0, 2, 3, 1};
        int** result = (int**)malloc(n*sizeof(int*));
		
		for(i=0;i<n;i++)
			result[i] = (int*)malloc(n*sizeof(int));
 
        for (int r = 0; r < n; r++) {
            for (int c = 0; c < n; c++) {
                int grid = (r / halfN) * 2 + (c / halfN);
                result[r][c] = subGrid[r % halfN][c % halfN];
                result[r][c] += gridFactors[grid] * subGridSize;
            }
        }
 
        int nColsLeft = halfN / 2;
        int nColsRight = nColsLeft - 1;
 
        for (int r = 0; r < halfN; r++)
            for (int c = 0; c < n; c++) {
                if (c < nColsLeft || c >= n - nColsRight
                        || (c == nColsLeft && r == nColsLeft)) {
 
                    if (c == 0 && r == nColsLeft)
                        continue;
 
                    int tmp = result[r][c];
                    result[r][c] = result[r + halfN][c];
                    result[r + halfN][c] = tmp;
                }
            }
 
        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;
		
		for(i=0;i<rows;i++){
			for(j=0;j<rows;j++){
				printf("%*s%d",rows - numDigits(square[i][j]),"",square[i][j]);
			}
			printf("\n");
		}
		printf("\nMagic constant: %d ", (rows * rows + 1) * rows / 2);
	}
	
	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(singlyEvenMagicSquare(n),n);
		}
		return 0;
	}


  

You may also check:How to resolve the algorithm Möbius function step by step in the 11l programming language
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the GAP programming language
You may also check:How to resolve the algorithm Host introspection step by step in the Rust programming language
You may also check:How to resolve the algorithm Determine if a string has all unique characters step by step in the Ada programming language
You may also check:How to resolve the algorithm Date format step by step in the Lua programming language