'Incorrect output for GCF calculator
My goal is to create a calculator that takes the user's input and determines factor pairs and the GCF. I'm trying to get my output to correspond with my professor and I am at a loss as to what could be incorrect. His required output is:
Enter the first number:
24
Enter the second number:
36
The factor pairs of 24 are: {1, 2, 3, 4, 6, 8, 12, 24}.
The factor pairs of 36 are: {1, 2, 3, 4, 6, 6, 9, 12, 18, 36}.
The greatest common factor (GCF) of 24 and 36 is 12.
however, my results are:
The factor pairs of 36 are: {1, 2, 3, 4, 6, 9, 12, 18, 36}.
Then for the GCF for inputs 25, and 30 my results are:
The factor pairs of 25 are: {1, 5, 25}.
The factor pairs of 30 are: {1, 2, 3, 5, 6, 10, 15, 30}.
The greatest common factor (GCF) of 25 and 30 is 25.
but the required output is:
The greatest common factor (GCF) of 25 and 30 is 5.
Here is my code for processing the factor pairs and the GCF:
public static void greatCF (Scanner sc){
System.out.println("\nEnter the first number:");
int num1 = sc.nextInt();
System.out.println("Enter the second number:");
int num2 = sc.nextInt();
System.out.print("The factor pairs of " + num1 + " are: {");
for(int i = 1; i <= num1; i++)
if (num1 % i == 0){
System.out.print(i);
if (i < num1){
System.out.print(", ");
}
}
System.out.println("}.");
System.out.print("The factor pairs of " + num2 + " are: {");
for(int j = 1; j <= num2; j++)
if (num2 % j == 0){
System.out.print(j);
if (j < num2){
System.out.print(", ");
}
}
System.out.println("}.");
int gcd = 1;
for (int b = 1; b <= num1 && b <= num2; b++){
if(num1 % b == 0 && num2 % b==0);
gcd = b;
}
System.out.println("The greatest common factor (GCF) of " + num1 + " and " + num2 + " is " + gcd + ".");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
