Program to find HCF of two numbers by iterative approach:
package quipoin.javaeasyprograms;
public class HCF {
static int findHcf(int x, int y) {
int n = Math.min(x, y);
for (int i = n; i >= 1; i--) {
if (x % i == 0 && y % i == 0) {
return i;
}
}
return 0;
}
public static void main(String[] args) {
System.out.println(findHcf(27, 18));
System.out.println(findHcf(5, 18));
}
}
Output:
9
1
Program to find HCF of two numbers by recursive approach:
package quipoin.javaeasyprograms;
public class HCF {
static int findHcf(int x, int y) {
if(x==0)
return y;
else
return findHcf(y%x,x);
}
public static void main(String[] args) {
System.out.println(findHcf(18, 24));
System.out.println(findHcf(5, 18));
}
}
Output:
72
1