
Patrick B. answered 04/20/20
Math and computer tutor/teacher
I would use recursion... here's the code
//*********************************************************************************/
class PrimeFactors
{
private long longIntNum;
public PrimeFactors( long L)
{
longIntNum = L;
}
public void Go ( long L)
{
boolean factor_found = false;
int i=2;
// looks for a prime factor between 2 and half the number
for (i=2; i<L/2+1; i++)
{
if ((L % i)==0) // found one !!! prints it and bails
{
System.out.println(i + " is a prime factor ");
factor_found=true;
break;
}
}
if (factor_found) // prime factor was found at loop counter i
{
L = L/i; // factors it out and repeats the process
Go(L);
}
else // we're done: there aren't any more factors
{
System.out.println( L + " is a prime factor ");
}
}
public static void main( String args[])
{
if (args.length>0) // passes the input number of the command line
{
long longIntNum = Long.parseLong(args[0]);
if (longIntNum<0) //peels off the negative if neccesary
{
longIntNum = -1*longIntNum;
System.out.println(" -1 is a factor ");
}
PrimeFactors myPrimeFactors = new PrimeFactors(longIntNum);
myPrimeFactors.Go(longIntNum);
}
else
{
System.out.println(" Please pass the number on the command line:");
System.out.println(" java PrimeFactors longIntNum ");
}
}