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 m = 27, then the output will be 4, because 1111 mod 27 = 4.

To solve this, we will follow these steps −

Define a function util() . This will take 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
  • 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

n = 4
m = 27
print(solve(n, m))

Input

4, 27

Output

4

Updated on: 25-Oct-2021

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements