VOOZH about

URL: https://www.geeksforgeeks.org/dsa/python-program-for-number-of-solutions-to-modular-equations/

⇱ Python Program for Number of Solutions to Modular Equations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Program for Number of Solutions to Modular Equations

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).


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

Explanation:

  • diff = A - B -> Finds the difference to analyze divisors.
  • diff % i == 0 -> Checks if i divides (A - B) evenly.
  • i > B and (diff // i) > B -> Only counts divisors greater than B.
  • Counts all valid divisors and prints the result.

Using math.sqrt()

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


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

Explanation:

  • math.sqrt() calculates the integer square root limit for iteration.
  • Divisors and their pairs are checked and counted if greater than B.
  • The final count gives all valid X values satisfying A % X == B.

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.


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

Explanation:

  • Loops through all possible X values from B + 1 to A.
  • Uses A % X == B to verify the condition.
Comment
Article Tags:
Article Tags: