Syntax error Find First element in AP which is multiple of given Prime in Python

Find First element in AP which is multiple of given Prime in Python



Suppose we have a first term (A) and common difference (d) of an AP series, and we also have a prime number P, we have to find the position of the first element in the given AP which is the a multiple of the given prime number P.

So, if the input is like A = 3, D = 4, P = 5, then the output will be 3 as fourth term of the given AP is a multiple of the prime number 5. So, first term = 3, second term = 3+4 = 7, third term = 3+2*4 = 11 and fourth term = 3+3*4 = 15.

To solve this, we will follow these steps −

  • Define a function get_pow() . This will take x, y, p

  • ans := 1

  • x := x mod p

  • while y > 0, do

    • if y AND 1 is non-zero, then

      • ans :=(ans * x) mod p

    • y := y/2

    • x :=(x * x) mod p

  • return ans

  • From the main method, do the following −

  • A := A mod P

  • D := D mod P

  • if A is same as 0, then

    • return 0

  • otherwise when D is same as 0, then

    • return -1

  • otherwise,

    • X := get_pow(D, P - 2, P)

    • return(X *(P - A)) mod P

Example

Let us see the following implementation to get better understanding −

 Live Demo

def get_pow(x, y, p) :
   ans = 1
   x = x % p
   while y > 0 :
      if y & 1 :
         ans = (ans * x) % p
      y = y >> 1
      x = (x * x) % p
   return ans
def get_nearest(A, D, P) :
   A %= P
   D %= P
   if A == 0 :
      return 0
   elif D == 0 :
      return -1
   else :
      X = get_pow(D, P - 2, P)
      return (X * (P - A)) % P

A = 3
D = 4
P = 5
print(get_nearest(A, D, P))

Input

A = 3 D = 4 P = 5

Output

3
Updated on: 2020-08-25T09:13:48+05:30

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements