-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcd.java
More file actions
53 lines (49 loc) · 2.13 KB
/
lcd.java
File metadata and controls
53 lines (49 loc) · 2.13 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
public class lcd {
public static void main(String[] args) {
int x = 6;
int y = 23;
int a = 7;
int b = 3;
System.out.println("Single method LCD: "+leastCommonDenominatorsngl(x, y, a , b));
System.out.println("LCD ethod w/ GCD helper: "+leastCommonDenominatordbl(x, y, a, b));
System.out.println("For loop method LCD: "+leastCommonDenominatorLoop(x, y, a, b));
}
//Least common denominator method with recursion. Does not call any helper methods. I dislike this implementation
//because it is less clear what the code is actually doing.
//In order to make this method work as a single method I used the x variable as a flag so that on the last method call on the stack I can do
//the math to calculate LCD and in all other method calls above it in the stack I just return the GCD.
public static int leastCommonDenominatorsngl(int x, int y, int a, int b) {
if( y ==0){
return b;
}
int gcd = leastCommonDenominatorsngl(-Math.abs(x), b%y, a, y); //x is passed as negative as a flag so that the method returns the GCD
if( x<0){
return gcd;
}
else{ //in the last call on the stack x is positive and the gcd is use to calculate the LCD, can easily fail if user passes negative x values
return (y*b)/gcd;}
}
//Least common denominator method with recursion. in this case the recursive method in the gcd() method being called as a helper method
//I prefer this implementation because the code is much simpler and easy to read.
public static int leastCommonDenominatordbl(int x, int y, int a, int b){
int gcd = gcd(y, b);
return (y*b)/gcd;
}
public static int gcd(int a,int b){
if(a == 0){
return b;
}
return gcd(b%a,a);
}
//LCD without recursion
public static int leastCommonDenominatorLoop(int x, int y, int a, int b){
int gcdA = y;
int gcdB = b;
while(!(gcdA==0)){
int temp = gcdA;
gcdA = gcdB%gcdA;
gcdB= temp;
}
return (y*b)/gcdB;
}
}