HeadlinesBriefing favicon HeadlinesBriefing.com

Divisibility Check for Huge Numbers Using Modular Arithmetic

DEV Community •
×

A programmer stumbles on a 22‑digit string that dwarfs standard integer types. The challenge: determine if it is divisible by 101 without resorting to big‑integer libraries. The solution hinges on a simple, digit‑by‑digit method rooted in modular arithmetic and it runs in linear time making it ideal for large datasets.

At its core, the trick is to keep track of the remainder after each digit. Starting from zero, the algorithm updates the remainder with the formula: remainder = (remainder × 10 + digit) % divisor. This keeps the intermediate value tiny, never exceeding the divisor for all input sizes efficiently.

Implementing the method in PHP is straightforward. A loop iterates over the string, casts each character to an integer, and applies the update rule. The function returns true when the final remainder equals zero, proving the massive number is indeed divisible by the chosen modulus without any external libraries efficiently.

Why does this matter? In competitive programming and cryptographic checks, numbers can span millions of digits. This lightweight approach guarantees O(n) time and O(1) space, making it a go‑to technique for validating divisibility in resource‑constrained environments without relying on heavy libraries or arbitrary‑precision arithmetic and it scales effortlessly.