File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Algorithms/Searching Algorithms/Greatest Common Divisor/Java Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ /* Reads two command-line arguments p and q and computes the greatest
2+ * common divisor of p and q using Euclid's algorithm.
3+ *
4+ * Remarks
5+ * -----------
6+ * - may return the negative of the gcd if p is negative
7+ */
8+
9+ public class Euclid {
10+
11+ // recursive implementation
12+ public static int gcd (int p , int q ) {
13+ if (q == 0 ) return p ;
14+ else return gcd (q , p % q );
15+ }
16+
17+ // non-recursive implementation
18+ public static int gcd2 (int p , int q ) {
19+ while (q != 0 ) {
20+ int temp = q ;
21+ q = p % q ;
22+ p = temp ;
23+ }
24+ return p ;
25+ }
26+
27+ public static void main (String [] args ) {
28+ int p = Integer .parseInt (args [0 ]);
29+ int q = Integer .parseInt (args [1 ]);
30+ int d = gcd (p , q );
31+ int d2 = gcd2 (p , q );
32+ System .out .println ("gcd(" + p + ", " + q + ") = " + d );
33+ System .out .println ("gcd(" + p + ", " + q + ") = " + d2 );
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments