Python Program for Number of Solutions to Modular Equations (original) (raw)

Last Updated : 4 Nov, 2025

Given two integers A and B, the task is to find how many integer values of X satisfy the modular equation: **A mod X = B. Here, X is called a solution of the modular equation. In simple terms, find all integers X such that when A is divided by X, the remainder is B.

**For Example:

**Input: A = 26, B = 2
**Output: 6
Possible X values -> {3, 4, 6, 8, 12, 24}

From the definition of modulus:

A = X * Y + B --> A - B = X * Y

So, X must be a divisor of (A − B). Also, because remainder B must be strictly less than the divisor X, only those divisors of (A − B) that are greater than B are valid solutions.

Let’s explore different methods to do this in Python.

Using square-root divisor method

This is the fastest method to count all divisors of (A - B) that are greater than B using a single loop up to √(A - B).

Python `

A = 26 B = 2

When A and B are equal → Infinite solutions

if A == B: print("For A =", A, "and B =", B, ", X can take infinitely many values greater than", A)

When A is less than B → No solution possible

elif A < B: print("For A =", A, "and B =", B, ", X cannot take any value")

When A is greater than B

else: count = 0 diff = A - B sqrt_diff = int(diff ** 0.5)

for i in range(1, sqrt_diff + 1):
    if diff % i == 0:
        if i > B:
            count += 1
        if diff // i != i and diff // i > B:
            count += 1

print("For A =", A, "and B =", B, ", X can take", count, "values")

`

Output

For A = 26 and B = 2 , X can take 6 values

**Explanation:

Using math.sqrt()

This version uses the math module for clearer square root calculation and keeps the logic simple.

Python `

import math A = 21 B = 5

if A == B: print("For A =", A, "and B =", B, ", X can take infinitely many values greater than", A)

elif A < B: print("For A =", A, "and B =", B, ", X cannot take any value")

else: count = 0 N = A - B limit = int(math.sqrt(N))

for i in range(1, limit + 1):
    if N % i == 0:
        if i > B:
            count += 1
        if N // i != i and N // i > B:
            count += 1

print("For A =", A, "and B =", B, ", X can take", count, "values")

`

Output

For A = 21 and B = 5 , X can take 2 values

**Explanation:

Using brute force check

This method checks every possible X from B + 1 to A and counts those that satisfy the modular equation. It’s simple but not efficient for large numbers.

Python `

A = 26 B = 2

if A == B: print("For A =", A, "and B =", B, ", X can take infinitely many values greater than", A)

elif A < B: print("For A =", A, "and B =", B, ", X cannot take any value")

else: count = 0 for X in range(B + 1, A + 1): if A % X == B: count += 1

print("For A =", A, "and B =", B, ", X can take", count, "values")

`

Output

For A = 26 and B = 2 , X can take 6 values

**Explanation: