Magic constant

From Rosetta Code
Revision as of 18:45, 8 November 2021 by Thundergnat (talk | contribs) (New draft task and Raku example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Magic constant is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant.

EG

A 3 x 3 magic square always sums to 15.

    ┌───┬───┬───┐
    │ 2 │ 7 │ 6 │
    ├───┼───┼───┤
    │ 9 │ 5 │ 1 │
    ├───┼───┼───┤
    │ 4 │ 3 │ 8 │
    └───┴───┴───┘

A 4 x 4 magic square always sums to 34.

Traditionally, the sequence leaves off terms for n = 0 and n = 1 as the magic squares of order 0 and 1 are trivial; and a term for n = 2 because it is impossible to form a magic square of order 2.


Task
  • Starting at order 3, show the first 20 magic constants.
  • Show the 1000th magic constant. (Order 1003)
  • Find and show the order of the smallest N x N magic square whose constant is greater than 10¹ through 10¹⁰.


Stretch
  • Find and show the order of the smallest N x N magic square whose constant is greater than 10¹¹ through 10²⁰.


See also


Raku

<lang perl6>use Lingua::EN::Numbers:ver<2.8+>;

my @magic-constants = lazy (3..∞).hyper.map: { (1 + .²) * $_ / 2 };

put "First 20 magic constants: ", @magic-constants[^20]»., say "1000th magic constant: ", @magic-constants[999]., say "\nSmallest order magic square with a constant greater than:";

(1..20).map: -> $p {printf "10%-2s: %s\n", $p.&super, comma 3 + @magic-constants.first( * > exp($p, 10), :k ) }</lang>

Output:
First 20 magic constants: 15 34 65 111 175 260 369 505 671 870 1,105 1,379 1,695 2,056 2,465 2,925 3,439 4,010 4,641 5,335
1000th magic constant: 503,006,505

Smallest order magic square with a constant greater than:
10¹ : 3
10² : 6
10³ : 13
10⁴ : 28
10⁵ : 59
10⁶ : 126
10⁷ : 272
10⁸ : 585
10⁹ : 1,260
10¹⁰: 2,715
10¹¹: 5,849
10¹²: 12,600
10¹³: 27,145
10¹⁴: 58,481
10¹⁵: 125,993
10¹⁶: 271,442
10¹⁷: 584,804
10¹⁸: 1,259,922
10¹⁹: 2,714,418
10²⁰: 5,848,036