โ† Flipkart questions

Multi-threaded factorial calculation

Filed under Flipkart

Free read 2 of 3

Define how the factorial computation is partitioned across multiple threads (e.g., dividing ranges of multipliers).

The question

Implement a multi-threaded program to calculate the factorial of a number using thread pools or concurrent execution models.

Constraints

  • Input number should be non-negative.
  • Must utilize concurrency constructs like thread pools or futures.
  • Handle potential thread synchronization safely.

Examples

Input
n = 5
Output
120
Why
Factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.

Approach

  1. Define how the factorial computation is partitioned across multiple threads (e.g., dividing ranges of multipliers).

Solution

O(n / num_threads + log n) time, O(num_threads) space

Python
import concurrent.futures
import math

def multiply_range(start, end):
    return math.prod(range(start, end + 1))

def parallel_factorial(n, num_threads=4):
    if n < 2:
        return 1
    chunk_size = max(1, n // num_threads)
    ranges = []
    for i in range(1, n + 1, chunk_size):
        ranges.append((i, min(n, i + chunk_size - 1)))
    with concurrent.futures.ThreadPoolExecutor(max_workers=num_threads) as executor:
        futures = [executor.submit(multiply_range, r[0], r[1]) for r in ranges]
        results = [f.result() for f in futures]
    return math.prod(results)

Tips

  • What they are testing: Test with edge inputs like 0 and 1, as well as larger numbers to verify parallel reduction correctness.
  • Common mistake: Overcomplicating thread management for simple arithmetic operations where overhead outweighs concurrency benefits.

Related Flipkart questions

Collected from public candidate posts and coding forums. Updated Nov 2026.