
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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)
- Related Articles
- C++ Program to Implement Russian Peasant Multiplication
- Python program multiplication of two matrix.
- Program to find maximum score from performing multiplication operations in Python
- Russian Doll Envelopes in C++
- Tuple multiplication in Python
- C++ Program to Generate Multiplication Table
- C++ Program to Perform Matrix Multiplication
- Java Program to Generate Multiplication Table
- Swift Program to Generate Multiplication Table
- Kotlin Program to Generate Multiplication Table
- Haskell Program to Generate Multiplication Table
- C++ Program to Implement Booth’s Multiplication Algorithm for Multiplication of 2 signed Numbers
- Russian Society Before the Revolution
- C++ Program to Perform Complex Number Multiplication
- C Program to represent a multiplication table.

Advertisements