Algorithm E (Extended Euclid’s algorithm). Given two positive integers m
and n, we compute their greatest common divisor d and two integers a and b,
such that am + bn = d.
E1. [Initialize.] Set a’ <– b <– 1, a <– b’ <– 0, c <– m, d <– n.
E2. [Divide.] Let q and r be the quotient and remainder, respectively, of c
divided by d. (We have c = qd + r and 0 <= r < d.)
E3. [Remainder zero?] If r = 0, the algorithm terminates; we have in this case
am + bn = d as desired.
E4. [Recycle.] Set c <– d, d <– r, t <– a’, a’ <– a, a <– t-qa, t <– b’, b’ <– b,
b <– t-qb, and go back to E2. |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created with IntelliJ IDEA.
* User: 1O1O
* Date: 12/16/13
* Time: 6:52 PM
* :)~
* Extended Euclid's Algorithm:ALGORITHMS
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m, n, a1, b, a, b1, c, d, q, r, t;
do{
System.out.print("Please input a positive integer for m:");
m = Integer.parseInt(br.readLine());
System.out.print("Please input a positive integer for n:");
n = Integer.parseInt(br.readLine());
a1=b=1;
a=b1=0;
c=m;
d=n;
do{
q = c/d;
r = c%d;
if(r == 0){
System.out.println("The greatest common divisor of m and n is:"+d);
System.out.println("am+bn="+"("+a+")"+"*"+"("+m+")"+"+"+"("+b+")"+"*"+"("+n+")"+"="+(a*m+b*n));
System.out.println("d="+d);
if(a*m+b*n == d){
System.out.println("am+bn = d");
}else {
System.out.println("am+bn != d");
}
System.out.println();
break;
}else {
c = d;
d = r;
t = a1;
a1 = a;
a = t-q*a;
t = b1;
b1 = b;
b = t-q*b;
}
}while (true);
}while (true);
}
}
Please input a positive integer for m:13
Please input a positive integer for n:13
The greatest common divisor of m and n is:13
am+bn=(0)*(13)+(1)*(13)=13
d=13
am+bn = d
Please input a positive integer for m:13
Please input a positive integer for n:3
The greatest common divisor of m and n is:1
am+bn=(1)*(13)+(-4)*(3)=1
d=1
am+bn = d
Please input a positive integer for m:3
Please input a positive integer for n:13
The greatest common divisor of m and n is:1
am+bn=(-4)*(3)+(1)*(13)=1
d=1
am+bn = d
Please input a positive integer for m:6
Please input a positive integer for n:12
The greatest common divisor of m and n is:6
am+bn=(1)*(6)+(0)*(12)=6
d=6
am+bn = d
Please input a positive integer for m:12
Please input a positive integer for n:6
The greatest common divisor of m and n is:6
am+bn=(0)*(12)+(1)*(6)=6
d=6
am+bn = d
Please input a positive integer for m:123456789
Please input a positive integer for n:987654321
The greatest common divisor of m and n is:9
am+bn=(-8)*(123456789)+(1)*(987654321)=9
d=9
am+bn = d
Please input a positive integer for m:
<< The Art of Computer Programming: Fundamental Algorithms>> VOLUME 1, DONALD E. KNUTH