How do i write a source code in java that finds the non-trivial factors of a number
e.g
Case : 2 is prime.
Case : 3 is prime.
Case : 5 is prime.
Case : 7 is prime.
Case : 10 has factor(s): 2 5
Case : 12 has factor(s): 2 3 4 6
Case : 18 has factor(s): 2 3 6 9
Case : 100 has factor(s): 2 4 5 10 20 25 50
Case : 97 is prime.
I currently have this code but it goes into an infinite 2... loop
public class Factors {
static ArrayList array = new ArrayList();
public static void main (String[]args) throws IOException
{
//Create a file
File myfile = new File ("Factors.in.txt");
Scanner scan = new Scanner (myfile);
int b = 1; // case counter
int i = 0;
while (scan.hasNextInt()){
int num = scan.nextInt();
if (isPrime(num) == true){
System.out.println("Case #" +b+ " " +num+" is prime");
b++;
}
else {
Factors(num,i);
System.out.print("Case #" +b+ " has factor(s)" );
for (int z = 0; z < array.size(); z++){
System.out.print(array.get(z) + " ");
}
i++;
}
i=0;
}
}
static boolean isPrime (int n)
{
if (n<=1) return false;
if (n==2) return true;
if (n%2==0) return false;
int m=(int)Math.round(Math.sqrt(n));
for (int i=3; i<=m; i+=2)
if (n%i==0)
return false;
return true;
}
static void Factors(int x,int y){
while (x > 3){
if (x%(x-1) == 0){
x = x-1;
array.add(y,x);
}
else {
x=x-1;
array.add(y,2);
}
}
}
}