Python Program for Find reminder of array multiplication divided by n

In this article, we will learn about finding the remainder when the product of all array elements is divided by a given number n. This approach uses modular arithmetic properties to avoid overflow issues.

Problem Statement

Given an array of numbers and a divisor n, we need to find the remainder after multiplying all array elements and dividing by n.

Approach

We use the distributive property of modular arithmetic to compute the result efficiently −

  • First, compute the remainder of each element like arr[i] % n. Then multiply this remainder with the current result.

  • After multiplication, again take the remainder to avoid overflow. This follows the distributive property of modular arithmetic.

Mathematical Foundation

The approach is based on this modular arithmetic property ?

( a * b ) % c = ( ( a % c ) * ( b % c ) ) % c

This property ensures that we can compute the final remainder without dealing with very large intermediate products.

Implementation

def find_remainder(arr, n):
    result = 1
    # Calculate remainder for each element and multiply
    for num in arr:
        result = (result * (num % n)) % n
    return result

# Example usage
numbers = [100, 1, 2, 3, 4, 5, 6, 6, 7]
divisor = 11

remainder = find_remainder(numbers, divisor)
print(f"Remainder when product is divided by {divisor}: {remainder}")
Remainder when product is divided by 11: 1

Step-by-Step Execution

Let's trace through the algorithm with our example ?

def find_remainder_detailed(arr, n):
    result = 1
    print(f"Initial result: {result}")
    
    for i, num in enumerate(arr):
        remainder = num % n
        result = (result * remainder) % n
        print(f"Step {i+1}: {num} % {n} = {remainder}, result = {result}")
    
    return result

numbers = [5, 3, 7]
divisor = 4

final_remainder = find_remainder_detailed(numbers, divisor)
print(f"\nFinal remainder: {final_remainder}")
Initial result: 1
Step 1: 5 % 4 = 1, result = 1
Step 2: 3 % 4 = 3, result = 3
Step 3: 7 % 4 = 3, result = 1

Final remainder: 1

Key Benefits

  • Prevents Overflow: By taking modulo at each step, we avoid large intermediate results

  • Efficient: Time complexity is O(n) where n is the array length

  • Space Efficient: Uses only constant extra space

Modular Arithmetic Process arr[i] % n = remainder × previous result % n

Conclusion

Using modular arithmetic properties, we can efficiently find the remainder of array multiplication divided by n. This approach prevents integer overflow and maintains O(n) time complexity while using constant space.

Updated on: 2026-03-25T06:29:35+05:30

835 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements