Algorithm E
Algorithm E (Euclid’s algorithm). Given two positive integers m and n, find
their greatest common divisor, that is, the largest positive integer that evenly
divides both m and n.
E1. [Find remainder.] Divide m by n and let r be the remainder. (We will have
0<= r < n.)
E2. [Is it zero?] If r = 0, the algorithm terminates; n is the answer.
E3. [Reduce.] Set m <– n, n <– r, and go back to step E1. |
Flow diagram
Java program
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created with IntelliJ IDEA.
* User: 1O1O
* Date: 12/15/13
* Time: 6:52 PM
* :)~
* Euclid's Algorithm:ALGORITHMS
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input a positive integer for m:");
int m = Integer.parseInt(br.readLine());
System.out.print("Please input a positive integer for n:");
int n = Integer.parseInt(br.readLine());
int r;
do{
r = m%n;
if(r == 0){
System.out.println("The greatest common divisor of m and n is:"+n);
break;
}else {
m = n;
n = r;
}
}while (true);
}
}
Inputs & Outputs
Please input a positive integer for m:12
Please input a positive integer for n:45
The greatest common divisor of m and n is:3
Reference
<< The Art of Computer Programming: Fundamental Algorithms>> VOLUME 1, DONALD E. KNUTH