Im trying to solve this problem
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My code is this:
import java.math.BigInteger;
public class LargestPrimeFactor
{
public static boolean isPrime(BigInteger nbr)
{
boolean isNPrime=true;
BigInteger i = BigInteger.valueOf(2);
while (i.compareTo(nbr.divide(BigInteger.valueOf(2))) < 0)
{
if ((nbr.compareTo(i) != 0) && (nbr.mod(i).equals(BigInteger.ZERO)))
{
isNPrime = false;
break;
}
i=i.add(BigInteger.ONE);
}
if (isNPrime == true) return true;
else return false;
}
public static void main(String[] args)
{
String strNum = "600851475143";
BigInteger num = BigInteger.valueOf(Long.parseLong(strNum));
BigInteger i = BigInteger.valueOf(Long.parseLong(strNum)-1);
BigInteger answer=BigInteger.ZERO;
while(i.compareTo(BigInteger.ONE)>0)
{
if (num.mod(i).equals(BigInteger.ZERO) && isPrime(i)==true)
{
answer=i;
break;
}
i=i.subtract(BigInteger.ONE);
}
System.out.println(answer);
}
}
I think this code will work but it will take FOREVER to work, I waited about an hour and got no results...
anyone have any alternative code or any idea to get the right answer?