multithreading - Calculating factorial using multiple threads in Python -
i use python 2.7 , have task write function calculates factorial using multiple threads. tried using traditional recursive approach, like
def factorial(n): if n < 1: return 1 else: return n * factorial(n - 1)
but seems way doesn't suite multithreading. there ways calculate factorial using multiple threads?
in multi-threading applications best minimize data dependencies exists between different threads.
in recursive solution factorials have mentioned hard find calculations not depend on results of other calculations.
a distinct approach split factorial in multiple parts. example, 2 threads 1 this:
n! = [1 * 2 * 3 * .. * (n/2)] * [(n/2 + 1) * ... * n]
the first thread calculate value:
v1 = 1 * 2 * 3 * .. * (n/2)
the second thread calculate:
v2 = (n/2 + 1) * ... * n
and afterwards, when both threads finished, main thread compute n! = v1 * v2
.
this can generalized use k
threads splitting input factorial k
different parts instead of two, in above example.
Comments
Post a Comment