Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find remainder after dividing n number of 1s by m in Python
Suppose we have two numbers n and m. We have to find the remainder after dividing n number of 1s by m.
So, if the input is like n = 4 and m = 27, then the output will be 4, because 1111 mod 27 = 4.
Understanding the Problem
When we have n number of 1s, we create a number like:
- n = 1: Number is 1
- n = 2: Number is 11
- n = 3: Number is 111
- n = 4: Number is 1111
The mathematical representation of n ones is (10^n - 1) / 9.
Algorithm
To solve this, we will follow these steps ?
Define a function util() that takes x, n, m:
- y := 1
- while n > 0, do
- if n is odd, then
- y := (y * x) mod m
- x := (x * x) mod m
- n := floor of n/2
- if n is odd, then
- return y
From the main method return floor of (util(10, n, 9 * m) / 9)
Example
Let us see the following implementation to get better understanding ?
def util(x, n, m):
y = 1
while n > 0:
if n & 1:
y = (y * x) % m
x = (x * x) % m
n >>= 1
return y
def solve(n, m):
return util(10, n, 9 * m) // 9
# Test the function
n = 4
m = 27
result = solve(n, m)
print(f"Remainder when {n} ones divided by {m}: {result}")
# Verify with direct calculation
ones_number = int('1' * n)
direct_result = ones_number % m
print(f"Direct calculation: {ones_number} mod {m} = {direct_result}")
Remainder when 4 ones divided by 27: 4 Direct calculation: 1111 mod 27 = 4
How It Works
The algorithm uses modular exponentiation to efficiently compute (10^n - 1) / 9 mod m:
- The
util()function implements fast exponentiation using binary representation - We calculate
util(10, n, 9 * m)to get 10^n mod (9 * m) - Dividing by 9 gives us the remainder when n ones are divided by m
Alternative Approach
For smaller values of n, we can use a direct iterative approach ?
def solve_iterative(n, m):
remainder = 0
for i in range(n):
remainder = (remainder * 10 + 1) % m
return remainder
# Test both approaches
n = 4
m = 27
print(f"Optimized approach: {solve(n, m)}")
print(f"Iterative approach: {solve_iterative(n, m)}")
Optimized approach: 4 Iterative approach: 4
Conclusion
The modular exponentiation approach efficiently finds the remainder when n ones are divided by m. For large values of n, this method is significantly faster than creating the actual number with n ones.
