Triangular numbers: Difference between revisions

Created Nim solution.
(Added Perl)
(Created Nim solution.)
Line 919:
tetrahedral-root: 44355.777384073255
pentatopic-root: 4321.0
</pre>
 
=={{header|Nim}}==
As described in the task presentation, we start the sequences at index 1.
<syntaxhighlight lang="Nim">import std/[math, strformat, strutils]
 
 
proc printNSimplexNumbers(r, count, width: Positive; title: string) =
## Print the first "count" terms of the "r-simplex" sequence
## using "width" characters.
echo title
for n in 1..count:
stdout.write align($binom(n + r - 1, r), width)
stdout.write if n mod 5 == 0: '\n' else: ' '
echo()
 
printNSimplexNumbers(2, 30, 3, "First 30 triangular numbers:")
printNSimplexNumbers(3, 30, 4, "First 30 tetrahedral numbers:")
printNSimplexNumbers(4, 30, 5, "First 30 pentatopic numbers:")
printNSimplexNumbers(12, 30, 10, "First 30 12-simplex numbers:")
 
 
func triangularRoot(x: float): float =
## Return the triangular root of "x".
(sqrt(8 * x + 1) - 1) * 0.5
 
func tetrahedralRoot(x: float): float =
## Return the tetrahedral root of "x".
let t1 = 3 * x
let t2 = sqrt(t1 * t1 - 1 / 27)
result = cbrt(t1 + t2) + cbrt(t1 - t2) - 1
 
func pentatopicRoot(x: float): float =
## Return the pentatopic root of "x".
(sqrt(5 + 4 * sqrt(24 * x + 1)) - 3) * 0.5
 
for n in [int64 7140, 21408696, 26728085384, 14545501785001]:
echo &"Roots of {n}:"
for (title, f) in {"triangular: ": triangularRoot,
"tetrahedral:": tetrahedralRoot,
"pentatopic: ": pentatopicRoot}:
echo &" {title} {f(n.float):.6f}"
echo()
</syntaxhighlight>
 
{{out}}
<pre>First 30 triangular numbers:
1 3 6 10 15
21 28 36 45 55
66 78 91 105 120
136 153 171 190 210
231 253 276 300 325
351 378 406 435 465
 
First 30 tetrahedral numbers:
1 4 10 20 35
56 84 120 165 220
286 364 455 560 680
816 969 1140 1330 1540
1771 2024 2300 2600 2925
3276 3654 4060 4495 4960
 
First 30 pentatopic numbers:
1 5 15 35 70
126 210 330 495 715
1001 1365 1820 2380 3060
3876 4845 5985 7315 8855
10626 12650 14950 17550 20475
23751 27405 31465 35960 40920
 
First 30 12-simplex numbers:
1 13 91 455 1820
6188 18564 50388 125970 293930
646646 1352078 2704156 5200300 9657700
17383860 30421755 51895935 86493225 141120525
225792840 354817320 548354040 834451800 1251677700
1852482996 2707475148 3910797436 5586853480 7898654920
 
Roots of 7140:
triangular: 119.000000
tetrahedral: 34.000000
pentatopic: 18.876647
 
Roots of 21408696:
triangular: 6543.000000
tetrahedral: 503.561166
pentatopic: 149.060947
 
Roots of 26728085384:
triangular: 231205.405565
tetrahedral: 5431.999939
pentatopic: 893.442457
 
Roots of 14545501785001:
triangular: 5393607.158145
tetrahedral: 44355.777377
pentatopic: 4321.000000
</pre>
 
256

edits