Program to find out the value of a given equation in Python

PythonServer Side ProgrammingProgramming

Suppose we are given five integer numbers a, b, c, d, n. We have to find out ((ab)(cd)) mod n. The output value is an integer number.

So, if the input is like a = 2, b = 3, c = 2, d = 4, n = 10, then the output will be 6.

2^3 = 8
2^4 = 16
8^16 = 281474976710656
281474976710656 mod 10 = 6

To solve this, we will follow these steps −

  • Define a function helper() . This will take n
    • p := n
    • i := 2
    • while i * i <= n, do
      • if n mod i is same as 0, then
        • p := p - floor value of (p / i)
      • while n mod i is same as 0, do
        • n := floor value of (n / i)
      • if i is not same as 2, then
        • i := i + 2
      • otherwise,
        • i := i + 1
    • if n > 1, then
      • p := p - floor value of (p / n)
    • return p
  • if b is same as 0 or (c is same as 0 and d is not same as 0) , then
    • return (a ^ 0) mod n
  • if c is same as 1 or d is same as 0, then
    • return (a ^ b) mod n
  • if a is same as 0 or a mod n is same as 0, then
    • return 0
  • if d is same as 1, then
    • return (a ^ b * c) mod n
  • p := helper(n)
  • e := (c ^ d) mod p + p
  • return (((a ^ b) mod n) ^ e) mod n

Example

Let us see the following implementation to get better understanding −

def helper(n):
   p = n
   i = 2
   while i * i <= n:
      if n % i == 0:
         p -= p // i
      while n % i == 0:
         n = n // i
      if i != 2:
         i += 2
      else:
         i += 1
   if n > 1:
      p -= p // n
   return p

def solve(a, b, c, d, n):
   if b == 0 or (c == 0 and d != 0):
      return pow(a, 0, n)
   if c == 1 or d == 0:
      return pow(a, b, n)
   if a == 0 or a % n == 0:
      return 0
   if d == 1:
      return pow(a, b * c, n)
   p = helper(n)
   e = pow(c, d, p) + p
   return pow(pow(a, b, n), e, n)

print(solve(2, 3, 2, 4, 10))

Input

2, 3, 2, 4, 10

Output

6
raja
Published on 20-Oct-2021 07:56:40
Advertisements