How to resolve the algorithm Magic squares of odd order step by step in the Rust programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Magic squares of odd order step by step in the Rust programming language
Table of Contents
Problem Statement
A magic square is an NxN square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, and both long (main) diagonals are equal to the same sum (which is called the magic number or magic constant). The numbers are usually (but not always) the first N2 positive integers. A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a semimagic square.
For any odd N, generate a magic square with the integers 1 ──► N, and show the results here.
Optionally, show the magic number.
You should demonstrate the generator by showing at least a magic square for N = 5.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Magic squares of odd order step by step in the Rust programming language
Source code in the rust programming language
fn main() {
let n = 9;
let mut square = vec![vec![0; n]; n];
for (i, row) in square.iter_mut().enumerate() {
for (j, e) in row.iter_mut().enumerate() {
*e = n * (((i + 1) + (j + 1) - 1 + (n >> 1)) % n) + (((i + 1) + (2 * (j + 1)) - 2) % n) + 1;
print!("{:3} ", e);
}
println!("");
}
let sum = n * (((n * n) + 1) / 2);
println!("The sum of the square is {}.", sum);
}
You may also check:How to resolve the algorithm Bulls and cows step by step in the Delphi programming language
You may also check:How to resolve the algorithm Create an HTML table step by step in the Erlang programming language
You may also check:How to resolve the algorithm Knight's tour step by step in the BASIC programming language
You may also check:How to resolve the algorithm Palindromic gapful numbers step by step in the Fōrmulæ programming language
You may also check:How to resolve the algorithm Filter step by step in the Clean programming language