44 views

Uploaded by jimi45

Geek Squares

- George PH Styan - An Introduction to Yantra Magic Squares & Agrippa-type Magic Matrices [72pp]
- Decimal
- worksheet1
- Most Important One Liner Questions of April Part II
- Exam1-StudyGuide
- Bhu Pet 2011 m.sc. Computer Sc
- Data Structures and Algorithms Bubble Sort
- IEEE A4 Format
- Hibernate
- Pattern Discovery 11.1
- Linear Suffix Array Construction by Almost Pure Induced-Sorting
- CLR Explained
- Graph Summarization
- DataStructure - Graphs
- p17-schmeister
- Ocet Computer Science Final
- IEEE - Analyzing Data-Error Propagation Effects in High-Performance Computing (Utrera y Otros, 2016)
- lecture1.pdf
- Question and Ans
- hacktivity12.1

You are on page 1of 6

Custom Search

Menu

Magic Square

A magic square of order n is an arrangement of n^2 numbers, usually distinct integers, in a square, such that the 3.6

n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the

integers from 1 to n^2.

The constant sum in every row, column and diagonal is called the magic constant or magic sum, M. The magic constant of

a normal magic square depends only on n and has the following value:

M = n(n^2+1)/2

the magic constants are: 15, 34, 65, 111, 175, 260, ...

In this post, we will discuss how programmatically we can generate a magic square of size n. Before we go further,

consider the below examples:

-----------------------

2 7 6

9 5 1

4 3 8

Sum in each row & each column = 3*(3^2+1)/2 = 15

----------------------

9 3 22 16 15

2 21 20 14 8

25 19 13 7 1

18 12 6 5 24

11 10 4 23 17

Sum in each row & each column = 5*(5^2+1)/2 = 65

----------------------

20 12 4 45 37 29 28

11 3 44 36 35 27 19

2 43 42 34 26 18 10

49 41 33 25 17 9 1

40 32 24 16 8 7 48

31 23 15 14 6 47 39

22 21 13 5 46 38 30

Sum in each row & each column = 7*(7^2+1)/2 = 175

Did you ﬁnd any pattern in which the numbers are stored?

In any magic square, the ﬁrst number i.e. 1 is stored at position (n/2, n-1). Let this position be (i,j). The next number is

stored at position (i-1, j+1) where we can consider each row & column as circular array i.e. they wrap around.

Three conditions hold:

1. The position of next number is calculated by decrementing row number of previous number by 1, and incrementing

the column number of previous number by 1. At any time, if the calculated row position becomes -1, it will wrap around

to n-1. Similarly, if the calculated column position becomes n, it will wrap around to 0.

2. If the magic square already contains a number at the calculated position, calculated column position will be

converted by W eb2PDFConvert.com

decremented by 2, and calculated row position will be incremented by 1.

3. If the calculated row position is -1 & calculated column position is n, the new position would be: (0, n-2).

Example:

Magic Square of size 3

----------------------

2 7 6

9 5 1

4 3 8

Steps:

1. position of number 1 = (3/2, 3-1) = (1, 2)

2. position of number 2 = (1-1, 2+1) = (0, 0)

3. position of number 3 = (0-1, 0+1) = (3-1, 1) = (2, 1)

4. position of number 4 = (2-1, 1+1) = (1, 2)

Since, at this position, 1 is there. So, apply condition 2.

new position=(1+1,2-2)=(2,0)

5. position of number 5=(2-1,0+1)=(1,1)

6. position of number 6=(1-1,1+1)=(0,2)

7. position of number 7 = (0-1, 2+1) = (-1,3) // this is tricky, see condition 3

new position = (0, 3-2) = (0,1)

8. position of number 8=(0-1,1+1)=(-1,2)=(2,2) //wrap around

9. position of number 9=(2-1,2+1)=(1,3)=(1,0) //wrap around

C/C++

converted by W eb2PDFConvert.com

// C program to generate odd sized magic squares

#include<stdio.h>

#include<string.h>

// A function to generate odd sized magic squares

void generateSquare(int n)

{

int magicSquare[n][n];

// set all slots as 0

memset(magicSquare, 0, sizeof(magicSquare));

// Initialize position for 1

int i = n/2;

int j = n-1;

// One by one put all values in magic square

for (int num=1; num <= n*n; )

{

if (i==-1 && j==n) //3rd condition

{

j = n-2;

i = 0;

}

else

{

//1st condition helper if next number

// goes to out of square's right side

if (j == n)

j = 0;

//1st condition helper if next number

// is goes to out of square's upper side

if (i < 0)

i=n-1;

}

if (magicSquare[i][j]) //2nd condition

{

j -= 2;

i++;

continue;

}

else

magicSquare[i][j] = num++; //set number

j++; i--; //1st condition

}

// Print magic square

printf("The Magic Square for n=%d:\nSum of each row or column %d:\n\n",

n, n*(n*n+1)/2);

for(i=0; i<n; i++)

{

for(j=0; j<n; j++)

printf("%3d ", magicSquare[i][j]);

printf("\n");

}

}

// Driver program to test above function

int main()

{

int n = 7; // Works only when n is odd

generateSquare (n);

return 0;

}

Run on IDE

Java

Python

Output:

converted by W eb2PDFConvert.com

The Magic Square for n=7:

Sum of each row or column 175:

20 12 4 45 37 29 28

11 3 44 36 35 27 19

2 43 42 34 26 18 10

49 41 33 25 17 9 1

40 32 24 16 8 7 48

31 23 15 14 6 47 39

22 21 13 5 46 38 30

References:

http://en.wikipedia.org/wiki/Magic_square

This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you ﬁnd

anything incorrect, or you want to share more information about the topic discussed above

Mathematical Matrix Login to Improve this Article

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:

Sieve of Eratosthenes

Find the row with maximum number of 1s

Magic Square | Even Order

Find day of the week for a given date

Find the number of islands | Set 1 (Using DFS)

Find sum of even factors of a number

Check if all digits of a number divide it

Find the perimeter of a cylinder

Program to implement Simpson’s 3/8 rule

Container with Most Water

(Login to Rate)

Average Diﬃculty : 3.6/5.0

3.6 Based on 45 vote(s) Add to TODO List

Basic Easy Medium Hard Expert

Mark as DONE

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.

Load Comments

Trending Content

converted by W eb2PDFConvert.com

Longest Common Subsequence Trending Content

Breadth First Traversal or BFS

School Programming

Longest Repeated Subsequence

Longest Palindromic Subsequence

Detect a negative cycle in a Graph | (Bellman Ford)

0-1 Knapsack Problem

GATE CS Notes

Depth First Traversal or DFS for a Graph

Reverse a linked list

Top 10 Algorithms and Data Structures for Competitive Programming

Top 10 algorithms in Interview Questions

How to begin with Competitive Programming?

Step by Step Guide for Placement Preparation

How to prepare for ACM-ICPC?

Insertion Sort , Binary Search , QuickSort , MergeSort , HeapSort

Popular Categories

Interview Experiences

Advanced Data Structures

Dynamic Programming

Greedy Algorithms

Backtracking

Pattern Searching

Divide & Conquer

Geometric Algorithms

Searching

Sorting

Analysis of Algorithms

Mathematical Algorithms

Randomized Algorithms

Recursion

Game Theory

Statistical Algorithms

ads by BSA

Tags

Advanced Data Structure Amazon Aptitude Aptitude Arrays Articles Bit Magic C C C++ C++ Quiz Computer Networks CPP-

Library C Quiz Data Structures Data Structures DBMS Dynamic Programming Experienced GBlog Geometric Graph Hash

Internship Interview Experiences Java Linked Lists Mathematical Matrix Microsoft number-digits

Program Output Project Puzzles Python QA - Placement Quizzes QA - Placement Quizzes School Programming

Searching series Sorting STL Strings Technical Scripter Trees

Advertise Here

Recent Comments

converted by W eb2PDFConvert.com

@geeksforgeeks, Some rights reserved Contact Us! About Us! Careers! Privacy Policy

converted by W eb2PDFConvert.com

- George PH Styan - An Introduction to Yantra Magic Squares & Agrippa-type Magic Matrices [72pp]Uploaded byBryan Pitkin
- DecimalUploaded byAIDARAZO7359
- worksheet1Uploaded byDwayne Fuller
- Most Important One Liner Questions of April Part IIUploaded byashu gupta
- Exam1-StudyGuideUploaded byBri Jackson
- Bhu Pet 2011 m.sc. Computer ScUploaded byaglasem
- Data Structures and Algorithms Bubble SortUploaded byEmmanuel Tuffet
- IEEE A4 FormatUploaded bySultan Khan
- HibernateUploaded bySabari Nathan
- Pattern Discovery 11.1Uploaded byRossana Cunha
- Linear Suffix Array Construction by Almost Pure Induced-SortingUploaded byRob Wentworth
- CLR ExplainedUploaded byAkshay Mehta
- Graph SummarizationUploaded byGaryo
- DataStructure - GraphsUploaded byaliyaraza1
- p17-schmeisterUploaded byMuhammad Zubair
- Ocet Computer Science FinalUploaded bybunty da
- IEEE - Analyzing Data-Error Propagation Effects in High-Performance Computing (Utrera y Otros, 2016)Uploaded byRigoberto José Martínez Cedeño
- lecture1.pdfUploaded byAnonymous pow3LFS
- Question and AnsUploaded bySatyajit Das
- hacktivity12.1Uploaded bys_gamal15
- Session 12Uploaded byshubhika gupta
- LabUploaded byZee Ard
- Lecture 17 bUploaded bykulandhaiswamychrist
- Center of Mass SpecificationsUploaded byJose Mari Cipriano
- lecture7.pptUploaded byAnonymous niE5VQOH
- Behavioral ReportUploaded byShawn Sagar
- Sorting 1Uploaded byDeepak Malusare
- mergesort-102-fa08Uploaded byAbrudan Bogdan
- 358 101 Interview and Quiz QuestionsUploaded byMankush Jain
- FM_ReportUploaded byrockyrr

- fibon_1Uploaded byjimi45
- Mentalism GuideUploaded byjimi45
- Learn MentalismUploaded byjimi45
- Pendulum NotesUploaded byjimi45
- Easy Magic Square 4uUploaded byjimi45
- The Power of LithomancyUploaded byjimi45
- lithomancy_1Uploaded byjimi45
- nlp_excellendeUploaded byjimi45
- Meanings About GemstonesUploaded byjimi45
- Necro NotesUploaded byjimi45
- Chinese Astro LogUploaded byjimi45
- Simple PendulumUploaded byjimi45
- Into Magic Square MathUploaded byjimi45
- Magic Square NewUploaded byjimi45
- Cork Magic TrickUploaded byjimi45
- astrologydetails_2Uploaded byjimi45
- dee_notes_1Uploaded byjimi45
- Qigong NotesUploaded byjimi45
- phi_notesUploaded byjimi45
- Golden Ratio 2Uploaded byjimi45
- Understanding Oauth 2Uploaded byjimi45
- jwt_badUploaded byjimi45
- Whatis AwsUploaded byjimi45
- Magic Square TheoryUploaded byjimi45
- Seance Rules 2Uploaded byjimi45
- Bend a SpoonUploaded byjimi45
- Pendulum 2Uploaded byjimi45
- Pendulum 1Uploaded byjimi45

- Vectors Summary With ExamplesUploaded byHuy Nguyen
- TEACHERS PERFORMANCE MANAGEMENT SYSTEM AT ISOMORPHIC HIGHER EDUCATIONAL INSTITUTIONS.Uploaded byIJAR Journal
- learningwithmickeyminnie lesson planUploaded byapi-294491980
- Siemens-PLM-star-ccm+-brochure-66560-A11Uploaded byDaniel Riveros
- _Bab 5 Peluang.pptUploaded byAmal Budiman
- ASTM C-403.pdfUploaded byrajeshji_000
- Input & OutputUploaded bymas akhbaruddin
- Guide for design elaboration of soil erosion prevention.pdfUploaded byGhita Raducan Anca Liana
- Circles TheoryUploaded bykishangopi123
- djwygesUploaded bydjw29
- Stats 250 W12 Exam 1 SolutionsUploaded byScott
- Baseband Sampling – GaussianWavesUploaded byNorozKhan
- 2013 october - november technical examination.docUploaded bythigz
- G-170-R0 Horizontal Vessel - Foundation Metric Sheets_2Uploaded bymicktunx
- Course outline emft EE 346 Spring 2016.docxUploaded byJhanzeb Khan
- Graphs Review[1]Uploaded byKarla Hoffman
- SOFiPLUS TutorialUploaded byMarko Vrca
- stoichiometryexplainedUploaded byfarooq_bagban
- TR Process Inspection NC II- Bklet RevUploaded byHarthwell Capistrano
- 239079566-Assembler-Book.pdfUploaded byborisg3
- Flexibility in Power Systems - Requirements, Modeling, And Evaluation - PhD Thesis - 2016Uploaded byM8ow6f
- CPR Compact Position Report Format FaaUploaded byAustrianSimon
- Museo Galileo CatalogueUploaded byAdministrador
- 102 Session 2Uploaded byapi-3719521
- Chemical KineticsUploaded byavg
- WEKA EcosystemUploaded byNous Tempa
- Fast Radix-2 Algorithm for the Discrete Hartley Transform of Type IIUploaded byManish Bansal
- distributed_dbms_tutorial.pdfUploaded byVivekananda Ganjigunta Narayana
- A Slug Test is a Controlled Field Experiment in Which the Water Level in a Control Well is Caused to ChangeUploaded byMalik Mohsin Tariq
- Wilson and Penzien DampingUploaded byAnonymous pEICfUhTPM