-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDivisors.java
More file actions
61 lines (56 loc) · 2.05 KB
/
Copy pathDivisors.java
File metadata and controls
61 lines (56 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class Divisors {
// Returns the greatest common divisor of a and b.
public static int gcd(int ax, int bx) {
int a = Math.max(Math.abs(ax), Math.abs(bx));
int b = Math.min(Math.abs(ax), Math.abs(bx));
int x, r;
if (a == 0 && b != 0) r = b;
else if (a != 0 && b == 0) r = a;
else if (a == 0) r = 0;
else {
do {
x = a;
a = b;
r = a;
b = x % b;
} while (b != 0);
}
return r;
}
// Returns the least common multiple of a and b.
public static int lcm(int a, int b) {
if (a == 0 || b == 0) return 0;
else return (Math.abs(a) / gcd(a, b)) * Math.abs(b);
}
// Returns true if a and b are relatively prime; false otherwise.
public static boolean areRelativelyPrime(int a, int b) {
if (gcd(a, b) == 1) return true;
else return false;
}
// Returns the number of integers between 1 and n that are
// relatively prime with n.
public static int totient(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (areRelativelyPrime(n, i)) {
count++;
}
}
return count;
}
// Takes two integer command-line arguments a and b
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
StdOut.println("gcd(" + a + "," + b + ") = " + gcd(a, b));
StdOut.println("lcm(" + a + "," + b + ") = " + lcm(a, b));
StdOut.println("areRelativelyPrime(" + a + "," + b + ") = " + areRelativelyPrime(a, b));
StdOut.println("totient(" + a + ") = " + totient(a));
StdOut.println("totient(" + b + ") = " + totient(b));
}
}