Skip to content

Commit b982f42

Browse files
Merge pull request #117 from adisiji/patch-2
Searching for GCD with Euclid in Java
2 parents 66a34e2 + 251aacb commit b982f42

File tree

1 file changed

+35
-0
lines changed
  • Algorithms/Searching Algorithms/Greatest Common Divisor/Java

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
}

0 commit comments

Comments
 (0)