Magic constant: Difference between revisions

Content added Content deleted
(Created Nim solution.)
Line 877: Line 877:
10^49 27144176165949066
10^49 27144176165949066
10^50 58480354764257322</pre>
10^50 58480354764257322</pre>

=={{header|Nim}}==
<syntaxhighlight lang="Nim">import std/[math, unicode]

func magicConstant(n: int): int =
## Return the magic constant for a magic square of order "n".
n * (n * n + 1) div 2

func minOrder(value: int): int =
## Return the smallest order such as the magic constant is greater than "value".
let start = int(cbrt(value.toFloat * 2))
result = start
while result.magicConstant < value:
inc result

const First = 3
const Superscripts: array['0'..'9', string] = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]

template order(idx: Positive): int =
## Compute the order of the magic square at index "idx".
idx + (First - 1)

func superscript(n: Natural): string =
## Return the Unicode string to use to represent an exponent.
for d in $n:
result.add(Superscripts[d])

echo "First 20 magic constants:"
for idx in 1..20:
stdout.write ' ', order(idx).magicConstant
echo()

echo "\n1000th magic constant: ", order(1000).magicConstant

echo "\nOrder of the smallest magic square whose constant is greater than:"
for n in 1..18:
let left = "10" & n.superscript & ':'
echo left.alignLeft(6), ($minOrder(10^n)).align(7)
</syntaxhighlight>

{{out}}
For the stretch task, as integers are 64 bits long, we are limited to 10^18. To go further, we would have to use external libraries such as <code>bigints</code>, <code>bignum</code> or <code>integers</code>.
<pre>First 20 magic constants:
15 34 65 111 175 260 369 505 671 870 1105 1379 1695 2056 2465 2925 3439 4010 4641 5335

1000th magic constant: 503006505

Order of the smallest magic square whose constant is greater than:
10¹: 3
10²: 6
10³: 13
10⁴: 28
10⁵: 59
10⁶: 126
10⁷: 272
10⁸: 585
10⁹: 1260
10¹⁰: 2715
10¹¹: 5849
10¹²: 12600
10¹³: 27145
10¹⁴: 58481
10¹⁵: 125993
10¹⁶: 271442
10¹⁷: 584804
10¹⁸: 1259922
</pre>

=={{header|Pascal}}==
=={{header|Pascal}}==
==={{header|Free Pascal}}===
==={{header|Free Pascal}}===