Program to apply Russian Peasant Multiplication in Python


Suppose we are given four integer numbers p, q, r, and k. We will use a method called the Russian Peasant Multiplication method and determine the value of (p + q.i)^r = r + s.i. We have to return the value of r mod k and s mod k.

So, if the input is like p = 3, q = 0, r = 8, k = 10000, then the output will be (6561, 0) 3^8 = 6561, as q = 0 value of r mod k = 6561.

To solve this, we will follow these steps −

  • if r is same as 0, then
    • return 1
  • therwise when r is same as 1, then
    • return a pair containing (p mod k, q mod k)
  • therwise when r mod 2 is same as 0, then
    • return solve((p*p - q*q) mod k, 2*p*q mod k, r/2, k)
  • therwise,
    • a pair (pr, qr) = solve(p, q, r-1, k)
    • return a pair containing ((p * pr - q * qr) mod k, (p * qr + q * pr) mod k)

Example

Let us see the following implementation to get better understanding −

def solve(p, q, r, k):
   if r == 0:
      return 1
   elif r == 1:
      return (p % k, q % k)
   elif r % 2 == 0:
      return solve((p*p - q*q) % k, 2*p*q % k, r/2, k)
   else:
      (pr, qr) = solve(p, q, r-1, k)
      return ((p * pr - q * qr) % k, (p * qr + q * pr) % k)

print(solve(3, 0, 8, 10000))

Input

3, 0, 8, 10000

Output

(6561, 0)

Updated on: 23-Oct-2021

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements