Program to find out the number of integral coordinates on a straight line between two points in Python


Suppose, we have been provided with two points (p1, q1) and (p2, q2). We have to find out the number of integral coordinates (both the x and y values are integers) if a straight line is drawn between the two given points. The number of points is returned.

So, if the input is like p1 = 3, q1 = 3, p2 = 6, q2 = 6, then the output will be 2 If we draw the straight line, we will see that the points (5,5) and (6,6) are situated on the straight line.

To solve this, we will follow these steps −

  • Define a function gcd_find() . This will take x,y
    • if y is same as 0, then
      • return x
    • return gcd_find(y, x mod y)

From the main method/function, do the following −

  • return gcd_find(|p2 - p1| , |q2 - q1|) - 1

Example

Let us see the following implementation to get better understanding −

def gcd_find(x,y):
   if y == 0:
      return x
   return gcd_find(y,x % y)

def solve(p1,q1,p2,q2):
   return gcd_find(abs(p2 - p1),abs(q2 - q1)) - 1

print(solve(3,3,6,6))

Input

3,3,6,6

Output

2

Updated on: 23-Oct-2021

186 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements