24 December 2020

The better way to calculate permutations programmatically

When wanting to calculate factorials and permutations, I was surprised that C++ didn't have a built-in function to do it. Sure, it's a simple function, but cmath could have had one instead of expecting users to write their own function. Anyway, I created a class for it and soon realized that even unsigned long long was unable to hold the large numbers that I was calculating permutations for.

This led me to the online calculators, which did ok for conditions like 81 numbers taken 81 at a time (which gives a huge result: 5797126020747367985879734231578109105412357244731625958745865049716390179693892056256184534249745940480000000000000000000).

However, calculations like 129600 taken 2 at a time, were not supported, so when I searched for which programming language could help, I found that Python was just perfect for this. Turns out, numbers in Python are only limited by the amount of RAM you have. Intelligent people, these people who maintain Python. 

Python does have a limit on how deep your recursion can go, so rather than use recursion to calculate factorials, it's better to use the humble for loop. Here's how it's done:

def factorial(n):
    fac = 1
    if n == 0:
        fac = 1
    else:
        for i in range(n,0,-1):
            fac = fac * i
    return fac

print("To calculate permutations:")
print("n!/(n-r)!")
n = int(input("Enter number of possibilities (n): "))
r = int(input("Enter how many at a time (r): "))
print("Permutations: ", factorial(n)/factorial(n-r))



No comments: