extended euclidean algorithm python code example
Example 1: extended euclidean python
def extendEuclidean(a, b, s1=1, s2=0, t1=0, t2=1):
if b:
r=a%b
return extendEuclidean(b, r, s2, s1-s2*(a
return a, s1, t1
Example 2: euclidean distance python
# I hope to be of help and to have understood the request
from math import sqrt # import square root from the math module
# the x and y coordinates are the points on the Cartesian plane
pointA = (x, y) # first point
pointB = (x, y) # second point
distance = calc_distance(pointA, pointB) # here your beautiful result
def calc_distance(p1, p2): # simple function, I hope you are more comfortable
return sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2) # Pythagorean theorem
Example 3: implementing euclid's extended algorithm
import java.util.Scanner;
class Lab3{
int euclid(int a, int b){
if(b==0)
return a;
else
return euclid(b, a%b);
}
int exeuclid(int a, int m)
{
int A3 = m;
int A2 = 0, A1 = 1;
if (m == 1)
return 0;
while (a > 1)
{
int q = a / m;
int t = m;
m = a % m;
a = t;
t = A2;
A2 = A1 - q * A2;
A1 = t;
}
if (A1 < 0)
A1 += A3;
return A1;
}
public static void main(String[] args) {
Lab3 ob = new Lab3();
int x, y, choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter Choice \n Enter 1 for gcd and 2 for extended ed");
choice=input.nextInt();
switch(choice)
{
case 1:
int output;
System.out.println("Enter the first number");
x = input.nextInt();
System.out.println("Enter the second number");
y = input.nextInt();
output = ob.euclid(x, y);
System.out.println("GCD is:"+output);
break;
case 2:
System.out.println("To Find Inverse");
int m, b;
System.out.println("Enter m");
m=input.nextInt();
System.out.println("Enter b");
b = input.nextInt();
System.out.println("Inverse is equal to: "+ob.exeuclid(m, b));
break;
default:
System.out.println("Wrong Choice");
}
}
}Code language: JavaScript (javascript)