Either use my PrimeFactorization class that I wrote here (the largest factor in the prime factorization result), or use just the necessary component of it (below) to find the largest prime factor.
DOWNLOAD
- import java.math.BigInteger;
- /**
- * The prime factors of 13195 are 5, 7, 13 and 29.
- * What is the largest prime factor of the number 600851475143 ?
- */
- public class Problem_3_Largest_Prime_Factor {
- public static void main(String[] args) {
- System.out.println(findLargestPrimeFactor(600851475143L));
- System.out.println(findLargestBigPrimeFactor(new BigInteger("600851475143")));
- }
- /**
- * Returns the largest prime factor of n.
- */
- public static long findLargestPrimeFactor(long n) {
- long primeFactor = 1L;
- long i = 2L;
- while (i <= n / i) {
- if (n % i == 0) {
- primeFactor = i;
- n /= i;
- } else {
- i++;
- }
- }
- if (primeFactor < n) primeFactor = n;
- return primeFactor;
- }
- /**
- * Returns the largest prime factor of n.
- */
- public static BigInteger findLargestBigPrimeFactor(BigInteger n) {
- BigInteger primeFactor = BigInteger.ONE;
- BigInteger i = new BigInteger("2");
- while (i.compareTo(n.divide(i)) <= 0) {
- if (n.mod(i).longValue() == 0) {
- primeFactor = i;
- n = n.divide(i);
- } else {
- i = i.add(BigInteger.ONE);
- }
- }
- if (primeFactor.compareTo(n) < 0) primeFactor = n;
- return primeFactor;
- }
- }
Created: May 11, 2014
Last Updated: May 10, 2020
Completed in full by: Michael Yaworski