Q10. Find LCM and GCD of given 2 numbers. Try both recursive and iterative function for GCD.
Answer:
public class Mathematics10 {
public static int getGCDRecursive(int m, int n) {
if (n == 0) {
return m;
} else {
return getGCDRecursive(n, m % n);
}
}
public static int getGCDIterative(int m, int n) {
if (n == 0) {
return m;
} else {
while (n != 0) {
int remainder = m % n;
m = n;
n = remainder;
}
return m;
}
}
public static int getLCM(int m, int n) {
return (m * n) / getGCDRecursive(m, n);
}
public static void main(String[] args) {
System.out.println("GCD of 40, 10 = " + getGCDRecursive(40, 10));
System.out.println("GCD of 24, 40 = " + getGCDRecursive(24, 40));
System.out.println("GCD of 40, 10 = " + getGCDIterative(40, 10));
System.out.println("GCD of 24, 40 = " + getGCDIterative(24, 40));
System.out.println("LCM of 40, 10 = " + getLCM(40, 10));
System.out.println("LCM of 24, 40 = " + getLCM(24, 40));
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.