-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhcf.java
More file actions
46 lines (40 loc) · 1.41 KB
/
Copy pathhcf.java
File metadata and controls
46 lines (40 loc) · 1.41 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
import java.util.Scanner;
public class hcf {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// input for the first number
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
// input for the second number
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.println("Factors of " + num1 + ":");
// calling the fucntion for generating the factors
printFactors(num1);
System.out.println("Factors of " + num2 + ":");
// calling the method for generating the factors
printFactors(num2);
// finding the hcf by calling the function
int hcf = findHCF(num1, num2);
System.out.println("HCF of " + num1 + " and " + num2 + " is: " + hcf);
scanner.close();
}
//method for finding the factors
public static void printFactors(int num) {
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
}
// Method to find the HCF (Highest Common Factor) of two numbers
public static int findHCF(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}