Magic constant: Difference between revisions

→‎{{header|Wren}}: Now uses new BigInt cube root function rather than Num version - still quick (17 ms).
(→‎{{header|Wren}}: Updated version - now almost instant (13 ms).)
(→‎{{header|Wren}}: Now uses new BigInt cube root function rather than Num version - still quick (17 ms).)
Line 226:
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
This uses Julia's approach for the final parts though, as our BigInt class doesn't have a cube root function, we use Num (i.e. double precision floating point) arithmetic instead and then check that the answers are correct.
<lang ecmascript>import "./seq" for Lst
import "./fmt" for Fmt
import "./big" for BigInt
 
var magicConstant = Fn.new { |n| (n*n + 1) * n / 2 }
 
var ss = ["\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074",
"\u2075", "\u2076", "\u2077", "\u2078", "\u2079"]
 
var superscript = Fn.new { |n| (n < 10) ? ss[n] : (n < 20) ? ss[1] + ss[n - 10] : ss[2] + ss[0] }
 
System.print("First 20 magic constants:")
var mc20 = (3..22).map { |n| magicConstant.call(n) }.toList
for (chunk in Lst.chunks(mc20, 10)) Fmt.print("$5d", chunk)
 
Fmt.print("\n1,000th magic constant: $,d", magicConstant.call(1002))
 
System.print("\nSmallest order magic square with a constant greater than:")
for (i in 1..20) {
var goal = 10BigInt.ten.pow(i)
var order = ((goal * 2).cbrt).flooricbrt + 1
// accuracy check as we're using Num arithmetic to calculate the order
var bigGoal = BigInt.ten.pow(i)
var bigOrder = BigInt.new(order)
if (!(magicConstant.call(bigOrder) > bigGoal && magicConstant.call(bigOrder-1) <= bigGoal)) {
System.print("Order for 10^%(i) is inaccurate.")
}
Fmt.print("10$-2s : $,9i", superscript.call(i), order)
}</lang>
9,486

edits