Combinations and permutations: Difference between revisions

Add Lua implementation
(Add C# implementation)
(Add Lua implementation)
 
Line 1,922:
900 C 300 = 1743356373296446642960730765085718347630... (208 more digits)
1000 C 333 = 5776134553147651669777486323549601722339... (235 more digits)
</pre>
 
=={{header|Lua}}==
{{trans|Perl}}
<syntaxhighlight lang="Lua">
-- Helper function to display results in scientific notation corrected
function eshow(x)
local e = math.floor(x / math.log(10))
local exponentiated = math.exp(x - e * math.log(10))
-- Corrected format specifier from %.8Fe%+d to %.8e, and manually constructing the scientific notation if needed
return string.format("%.8e", exponentiated) .. "e" .. tostring(e)
end
 
-- The rest of the functions remain the same
 
-- Define the factorial function for permutations
function P(n, k)
local x = 1
for i = n - k + 1, n do
x = x * i
end
return x
end
 
-- Define the function for big permutations using logarithms
function P_big(n, k)
local x = 0
for i = n - k + 1, n do
x = x + math.log(i)
end
return eshow(x)
end
 
-- Define the combinations function
function C(n, k)
local x = 1
for i = 1, k do
x = x * (n - i + 1) / i
end
return x
end
 
-- Define the function for big combinations using logarithms
function C_big(n, k)
local x = 0
for i = 1, k do
x = x + math.log(n - i + 1) - math.log(i)
end
return math.exp(x)
end
 
-- Function to showcase the calculations
function showoff(text, code, fname, ...)
local n = {...}
print("\nA sample of " .. text .. " from " .. n[1] .. " to " .. n[#n] .. "")
for _, v in ipairs(n) do
local k = math.floor(v / 3)
print(v, fname .. " " .. k .. " = ", code(v, k))
end
end
 
-- Examples of usage
showoff("Permutations", P, "P", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
showoff("Combinations", C, "C", 10, 20, 30, 40, 50, 60)
showoff("Permutations", P_big, "P", 5, 50, 500, 1000, 5000, 15000)
showoff("Combinations", C_big, "C", 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000)
</syntaxhighlight>
{{out}}
<pre>
 
A sample of Permutations from 1 to 12
1 P 0 = 1
2 P 0 = 1
3 P 1 = 3
4 P 1 = 4
5 P 1 = 5
6 P 2 = 30
7 P 2 = 42
8 P 2 = 56
9 P 3 = 504
10 P 3 = 720
11 P 3 = 990
12 P 4 = 11880
 
A sample of Combinations from 10 to 60
10 C 3 = 120.0
20 C 6 = 38760.0
30 C 10 = 30045015.0
40 C 13 = 12033222880.0
50 C 16 = 4923689695575.0
60 C 20 = 4.1918445058055e+15
 
A sample of Permutations from 5 to 15000
5 P 1 = 5.00000000e+00e0
50 P 16 = 1.03017325e+00e26
500 P 166 = 3.53487492e+00e434
1000 P 333 = 5.96932629e+00e971
5000 P 1666 = 6.85674576e+00e6025
15000 P 5000 = 9.64985399e+00e20469
 
A sample of Combinations from 100 to 1000
100 C 33 = 2.9469242702254e+26
200 C 66 = 7.2697525451696e+53
300 C 100 = 4.158251463258e+81
400 C 133 = 1.2579486841822e+109
500 C 166 = 3.9260283861944e+136
600 C 200 = 2.5060177832203e+164
700 C 233 = 8.1032035633383e+191
800 C 266 = 2.6456233626831e+219
900 C 300 = 1.7433563732974e+247
1000 C 333 = 5.776134553149e+274
 
</pre>
 
338

edits