Skip to content

Instantly share code, notes, and snippets.

@BT-ICD
Created June 2, 2021 17:01
Show Gist options
  • Save BT-ICD/01af0f0e55b2458264119f24f8594305 to your computer and use it in GitHub Desktop.
Save BT-ICD/01af0f0e55b2458264119f24f8594305 to your computer and use it in GitHub Desktop.
Example to find HCF and LCM
/**
* Example: To find HCF - Highest Common Factor (also called Greatest Common Divisor)
* 60 and 40 is 20, i.e, HCF(60,40) = 20
* 100 and 150 is 50, i.e, HCF(150,50) = 50
* 144 and 24 is 24, i.e, HCF(144,24) = 24
* 17 and 89 is 1, i.e, HCF(17,89) = 1
* LCM of (72,120) = 360
* LCM of (15,20) = 60
* Learning Reference:
* https://byjus.com/maths/lcm-of-two-numbers/
* https://www.calculatorsoup.com/calculators/math/lcm.php
* */
public class HCFDEmo {
public static void main(String[] args) {
int a, b, i;
int hcf = 1;
int maxNum;
a= 15; // 30;
b=20; // 42;
maxNum=(a>b)?a:b;
for(i= 1 ;i<maxNum;i++){
if(a%i ==0 && b%i==0){
hcf =i;
}
}
int lcm = a*b/hcf;
System.out.println("HCF is:" + hcf);
System.out.println("LCM is: " + lcm);
}
}
@BT-ICD
Copy link
Author

BT-ICD commented Jun 2, 2021

Sample output:
HCF is:5
LCM is: 60

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment