Академический Документы
Профессиональный Документы
Культура Документы
Aim:- GCD of two numbers is the largest number that divides both of them. A simple way to
find GCD is to factorize both numbers and multiply common factors.
Theory:- While the Euclidean algorithm calculates only the greatest common divisor (GCD) of
two integers a and b, the extended version also finds a way to represent GCD in terms
of a and b, i.e. coefficients x and y for which:
It's important to note, that we can always find such a representation, for instance gcd(55,80)=5
therefore we can represent 55 as a linear combination with the terms 55 and 80: 55⋅3+80⋅(−2)=5.
A more general form of that problem is discussed in the article about Linear Diophantine
Equations. It will build upon this algorithm.
Algorithm :-
The changes to the original algorithm are very simple. If we recall the algorithm, we can see that
the algorithm ends with b=0 and a=g. For these parameters we can easily find coefficients,
namely g⋅1+0⋅0=g.
Starting from these coefficients (x,y)=(1,0), we can go backwards up the recursive calls. All we
need to do is to figure out how the coefficients x and y change during the transition
from (a,b) to (b,a mod b).
Let us assume we found the coefficients (x1,y1) for (b,a mod b):
g=a⋅y1+b⋅(x1−y1⋅⌊a/b⌋)g=a⋅y1+b⋅(x1−y1⋅⌊ab⌋)
{x=y1 ,y=x1−y1⋅⌊a/b⌋
Explanation:
A*x+B*y=gcd(A,B) .............................................(1)
Extended Euclidean Algorithm finds x and y for us.
=> B*x1 + (A%B)*y1 = gcd(A,B)
[This follows from the Euclidean Algorithm. Remember the recurrence
GCD(A,B)=GCD(B,A%B)]
=> B*x1 + (A-[A/B]*B)*y1 = gcd(A,B)
{[A/B] represents floor(A/B)}
Expanding,
B*x1 + A*y1 - [A/B]*B*y1 = gcd(A,B)
Taking B common,
B(x1-[A/B]*B) + A*y1 = gcd(A,B)
=> A*y1 + B*(x1-[A/B]*B) = gcd(A,B)......................(2)
Comparing 1 and 2,
x=y1 and y=x1-[A/B]*B
This shows that if y1 and x1 can be calculated we can calculate x and y.
Input
The input will consist of a set of lines with the integer numbers A and B, separated with space
(A;B < 1000000001).
Output
For each input line the output line should consist of three integers X, Y and D, separated with
space. If there are several such X and Y , you should output that pair for which jXj + jY j is the
minimal. If there are several X and Y satisfying the minimal criteria, output the pair for which X
≤Y.
Sample Input
4 6
17 17
Sample Output
-1 1 2
0 1 17
Conclusion:
In this Practical, I studied analyzing a property of an algorithm whose classification is not
known for all possible inputs using The Euclid Problem.
/*Student Name: Hitesh Raghunath Dhake. Class: T.E
Roll No: 16 Batch: T1
return gcd(b%a, a)
a = 10
b = 15
print("gcd(", a , "," , b, ") = ", gcd(a, b))
a = 35
b = 10
print("gcd(", a , "," , b, ") = ", gcd(a, b))
a = 31
b=2
print("gcd(", a , "," , b, ") = ", gcd(a, b))
Output:-