20. Create a class with the following methods:
i) int HCF(int a, int b), which returns the highest common factor (HCF) among the two integers a and b and return it.
ii) int LCM(int , int b), which returns the least common multiple (LCM) among the two integers a and b and return it.
Answers
Answer:
import java.util.*;
public class Main
{
static int hcf(int a , int b){
ArrayList<Integer> factors = new ArrayList<Integer>();
if(a > b){
for(int i = 2; i < a; i++){
if(a%i == 0 && b%i == 0){
factors.add(i);
}
}
}
if(b > a){
for(int i = 2; i < b; i++){
if(a%i == 0 && b%i == 0){
factors.add(i);
}
}
}
if(factors.isEmpty()){
return 1;
}
return Collections.max(factors);
}
static int lcm(int a , int b){
int gcd = 0;
for(int i = 1; i <= a && i <= b; ++i) {
if(a % i == 0 && b % i == 0)
gcd = i;
}
int lcm = (a * b) / gcd;
return lcm;
}
public static void main(String[] args) {
System.out.println(lcm(10,20));
System.out.println(hcf(200,600));
}
}
Explanation: