Magic constant: Difference between revisions
Content added Content deleted
(Created Nim solution.) |
(Used logarithm to avoid overflow in the stretch task.) |
||
Line 885: | Line 885: | ||
n * (n * n + 1) div 2 |
n * (n * n + 1) div 2 |
||
func minOrder( |
func minOrder(n: int): int = |
||
## Return the smallest order such as the magic constant is greater than " |
## Return the smallest order such as the magic constant is greater than "10^n". |
||
const Ln2 = ln(2.0) |
|||
const Ln10 = ln(10.0) |
|||
result = int(exp((Ln2 + n.toFloat * Ln10) / 3)) + 1 |
|||
while result.magicConstant < value: |
|||
inc result |
|||
const First = 3 |
const First = 3 |
||
Line 912: | Line 911: | ||
echo "\nOrder of the smallest magic square whose constant is greater than:" |
echo "\nOrder of the smallest magic square whose constant is greater than:" |
||
for n in 1.. |
for n in 1..20: |
||
let left = "10" & n.superscript & ':' |
let left = "10" & n.superscript & ':' |
||
echo left.alignLeft(6), ($minOrder( |
echo left.alignLeft(6), ($minOrder(n)).align(7) |
||
</syntaxhighlight> |
</syntaxhighlight> |
||
{{out}} |
{{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: |
<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 |
15 34 65 111 175 260 369 505 671 870 1105 1379 1695 2056 2465 2925 3439 4010 4641 5335 |
||
Line 943: | Line 941: | ||
10¹⁷: 584804 |
10¹⁷: 584804 |
||
10¹⁸: 1259922 |
10¹⁸: 1259922 |
||
10¹⁹: 2714418 |
|||
10²⁰: 5848036 |
|||
</pre> |
</pre> |
||