Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating factorial using multiple threads in Python

I use Python 2.7 and I have a task to write a function that calculates factorial using multiple threads. I tried to do that using traditional recursive approach, like

def factorial(n):
    if n < 1:
        return 1
    else:
        return n * factorial(n - 1)

But it seems that this way doesn't suite for multithreading. Are there any ways to calculate factorial using multiple threads?

like image 584
AlexNikolaev94 Avatar asked Apr 07 '17 08:04

AlexNikolaev94


People also ask

Can Python use multiple threads?

To recap, threading in Python allows multiple threads to be created within a single process, but due to GIL, none of them will ever run at the exact same time. Threading is still a very good option when it comes to running multiple I/O bound tasks concurrently.

How do you find the factorial of a string in Python?

factorial() in Python Because it has C type internal implementation, it is fast. math. factorial(x) Parameters : x : The number whose factorial has to be computed. Return value : Returns the factorial of desired number.


1 Answers

In multi-threading applications it is best to minimize the data dependencies that exists between the different threads.

In the recursive solution for factorials that you have mentioned it is hard to find calculations that do not depend on the results of other calculations.

A distinct approach would be to split the factorial in multiple parts. For example, for two threads one could do something like this:

n! = [1 * 2 * 3 * .. * (n/2)] * [(n/2 + 1) * ... * n]

The first thread would calculate the value:

v1 = 1 * 2 * 3 * .. * (n/2)

The second thread would calculate:

v2 = (n/2 + 1) * ... * n

And afterwards, when both threads are finished, the main thread would compute n! = v1 * v2.

This can be generalized to use k threads by splitting the input factorial into k different parts instead of just two, as in the above example.

like image 164
qwertyman Avatar answered Sep 30 '22 01:09

qwertyman