In this article I will show you a quick python script used to find the factorial of a number. Basically we need two steps to find the factorial of a number in this program.
- First we need to create a thread which runs on it’s own to run the program so the main thread will be freed to do the other job.
- Secondly we need to create a factorial function which will repeatedly calling itself until the base problem has been reached which the function will then return the answer to the caller.
Below is the entire python script where we will pass in a number to the new python thread and from there the program will find the factorial of that number.
import threading class factorialThread (threading.Thread): def __init__(self, factorial): threading.Thread.__init__(self) self.factorial = factorial #the number which we want to find it's factorial def run(self): int_factorial = self.factorialize(self.factorial) #call the factorialize function print("The factorial of number " + str(self.factorial) + " is " + str(int_factorial)) def factorialize(self, n): if (n == 1): return 1; else: return n * self.factorialize(n - 1); #the function will repeatedly calling itself until the base has been reached if __name__ == "__main__": # create new thread thread1 = factorialThread(20) # start the thread thread1.start()
Now just enter any number to that thread and you will get the factorial of that number, for example if you pass in 20 to that thread you will get…
The factorial of number 20 is 2432902008176640000
What a huge amount, a normal human certainly cannot do this in our head.