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 apply Russian Peasant Multiplication in Python
The Russian Peasant Multiplication method is an ancient algorithm for performing exponentiation of complex numbers of the form (p + q·i)^r using recursive multiplication. This method efficiently computes the result by breaking down the exponent using binary representation.
Given four integers p, q, r, and k, we need to calculate (p + q·i)^r = x + y·i and return (x mod k, y mod k).
Algorithm Steps
The Russian Peasant method follows these recursive steps:
- If r = 0, return 1 (any number to power 0 is 1)
- If r = 1, return (p mod k, q mod k) (base case)
- If r is even, use the identity: (a + bi)^(2n) = ((a² - b²) + 2ab·i)^n
- If r is odd, recursively compute (p + q·i)^(r-1) and multiply by (p + q·i)
Implementation
def russian_peasant_multiplication(p, q, r, k):
if r == 0:
return (1, 0) # (p + q*i)^0 = 1 + 0*i
elif r == 1:
return (p % k, q % k)
elif r % 2 == 0:
# For even powers: (a + bi)^(2n) = ((a² - b²) + 2ab*i)^n
new_p = (p * p - q * q) % k
new_q = (2 * p * q) % k
return russian_peasant_multiplication(new_p, new_q, r // 2, k)
else:
# For odd powers: multiply by (p + q*i) after computing (p + q*i)^(r-1)
pr, qr = russian_peasant_multiplication(p, q, r - 1, k)
real_part = (p * pr - q * qr) % k
imag_part = (p * qr + q * pr) % k
return (real_part, imag_part)
# Test with the given example
p, q, r, k = 3, 0, 8, 10000
result = russian_peasant_multiplication(p, q, r, k)
print(f"({p} + {q}i)^{r} mod {k} = {result}")
# Additional test cases
print(russian_peasant_multiplication(2, 1, 3, 1000)) # (2 + i)^3
print(russian_peasant_multiplication(1, 1, 4, 100)) # (1 + i)^4
(3 + 0i)^8 mod 10000 = (6561, 0) (2, 11) (96, 0)
How It Works
The algorithm uses the mathematical properties of complex number multiplication:
- Complex multiplication: (a + bi)(c + di) = (ac - bd) + (ad + bc)i
- Power reduction: For even exponents, it squares the base and halves the exponent
- Recursive approach: Reduces the problem size at each step, similar to binary exponentiation
Time Complexity
The time complexity is O(log r) since we halve the exponent at each recursive call for even powers, making it much more efficient than naive multiplication.
Conclusion
Russian Peasant Multiplication efficiently computes complex number exponentiation using recursive binary reduction. The algorithm handles both even and odd exponents optimally, making it ideal for large exponent calculations with modular arithmetic.
