Find maximum operations to reduce N to 1 in Python

We have two numbers P and Q that form N = P!/Q!. Our goal is to reduce N to 1 by performing the maximum number of operations possible. In each operation, we can replace N with N/X when N is divisible by X. We need to find the maximum number of operations possible.

The key insight is that the maximum number of operations equals the total count of prime factors in N. Since N = P!/Q!, we need to count prime factors in factorials efficiently.

Algorithm Approach

We use a sieve-like approach to precompute the count of prime factors for all numbers up to a limit, then use prefix sums to get factorial prime factor counts ?

  1. Create an array to store prime factor counts
  2. For each prime number, update counts for all its multiples
  3. Build prefix sums to get factorial prime factor counts
  4. Return the difference: factors[P] - factors[Q]

Implementation

N = 1000005
factors = [0] * N

def get_prime_facts():
    # Count prime factors for each number
    for i in range(2, N):
        if factors[i] == 0:  # i is prime
            for j in range(i, N, i):
                factors[j] = factors[j // i] + 1
    
    # Convert to prefix sums for factorial calculations
    for i in range(1, N):
        factors[i] += factors[i - 1]

def max_operations(a, b):
    return factors[a] - factors[b]

# Precompute prime factors
get_prime_facts()

# Example: P = 7, Q = 4
a = 7
b = 4
result = max_operations(a, b)
print(f"Maximum operations for P={a}, Q={b}: {result}")
Maximum operations for P=7, Q=4: 4

How It Works

For P = 7, Q = 4, we have N = 7!/4! = 7×6×5 = 210. The prime factorization of 210 is 2¹×3¹×5¹×7¹, giving us 4 prime factors total. Each division operation removes one prime factor, so we can perform exactly 4 operations ?

# Let's trace the example step by step
import math

P, Q = 7, 4
N = math.factorial(P) // math.factorial(Q)
print(f"N = {P}!/{Q}! = {N}")

# Prime factorization of 210
print(f"210 = 2¹ × 3¹ × 5¹ × 7¹")
print(f"Total prime factors: 1 + 1 + 1 + 1 = 4")

# Possible operations
operations = [210//2, 210//3, 210//5, 210//7]
print(f"Operations: 210?{operations}")
N = 7!/4! = 210
210 = 2¹ × 3¹ × 5¹ × 7¹
Total prime factors: 1 + 1 + 1 + 1 = 4
Operations: 210?[105, 70, 42, 30]

Time Complexity

The preprocessing takes O(N log log N) time using the sieve approach. Each query is answered in O(1) time after preprocessing.

Conclusion

The maximum operations to reduce P!/Q! to 1 equals the total count of prime factors in the result. We use efficient preprocessing with prefix sums to handle multiple queries quickly.

Updated on: 2026-03-25T09:45:30+05:30

325 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements