I wrote this program to determine the Greatest Common Factor of any 2 given numbers, and would like to know of any improvements that can be made. I have tested it using a loop and 2 randomly generated numbers and it seems to work perfectly:
import java.util.ArrayList;
import java.util.Scanner;
public class GreatestCommonFactor
{
public static void main(String[] args)
{
System.out.println("Please enter 2 numbers:");
Scanner in = new Scanner(System.in);
int a = Integer.parseInt(in.nextLine());
int b = Integer.parseInt(in.nextLine());
int greatestCommonFactor = gcf(a,b);
System.out.println(greatestCommonFactor);
in.close();
}
public static int gcf(int a, int b)
{
int result = 0;
ArrayList<Integer> factorsA = factorise(a);
ArrayList<Integer> factorsB = factorise(b);
for (int i = 0; i < factorsA.size(); i++)
if (factorsB.contains(factorsA.get(i)))
result = factorsA.get(i);
return result;
}
public static ArrayList<Integer> factorise(int num)
{
ArrayList<Integer> factors = new ArrayList<Integer>();
int bounds = num/2;
for (int i = 1; i <= bounds; i++)
if (num % i == 0)
factors.add(i);
factors.add(num);
return factors;
}
}