﻿ Multi-threaded factorial calculation in Python

## Python Multi-threading: Exercise-4 with Solution

Write a Python program to calculate the factorial of a number using multiple threads.

Sample Solution:

Python Code:

``````import threading

def factorial_of_a_anumber(n):
result = 1
for i in range(1, n+1):
result *= i
return result

def calculate_factorial(n):
result = factorial_of_a_anumber(n)

# Factorial of 12
n = 12

# Create threads for factorial calculation

# Wait for the threads to complete
``````

Sample Output:

```Calculating factorial of 12 in thread Thread-6

```

Explanation:

In this program, we define a "factorial_of_a_number()" function that calculates the factorial of a number n using a sequential loop. We also define a "calculate_factorial()" function that takes a number as input, prints a message indicating the current thread. It calls the "factorial_of_a_number()" function, and prints the result.

We then create two threads, thread1 and thread2, targeting the "calculate_factorial()" function with the same number as an argument. We start the threads using the start() method, which initiates their parallel execution. Finally, we use the join() method to wait for threads to complete.

When you run this program, it calculates the factorial of the given number in two separate threads.

Flowchart:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿