Project Euler Problem #3 - Largest Prime Factor (in Java)

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.

  1. import java.math.BigInteger;

  2. /**
  3.   * The prime factors of 13195 are 5, 7, 13 and 29.
  4.   * What is the largest prime factor of the number 600851475143 ?
  5.   */

  6. public class Problem_3_Largest_Prime_Factor {

  7.   public static void main(String[] args) {
  8.     System.out.println(findLargestPrimeFactor(600851475143L));
  9.     System.out.println(findLargestBigPrimeFactor(new BigInteger("600851475143")));
  10.   }

  11.   /**
  12.     * Returns the largest prime factor of n.
  13.     */
  14.   public static long findLargestPrimeFactor(long n) {
  15.     long primeFactor = 1L;
  16.     long i = 2L;

  17.     while (i <= n / i) {
  18.       if (n % i == 0) {
  19.         primeFactor = i;
  20.         n /= i;
  21.       } else {
  22.         i++;
  23.       }
  24.     }

  25.     if (primeFactor < n) primeFactor = n;

  26.     return primeFactor;
  27.   }

  28.   /**
  29.     * Returns the largest prime factor of n.
  30.     */
  31.   public static BigInteger findLargestBigPrimeFactor(BigInteger n) {
  32.     BigInteger primeFactor = BigInteger.ONE;
  33.     BigInteger i = new BigInteger("2");
  34.  
  35.     while (i.compareTo(n.divide(i)) <= 0) {
  36.       if (n.mod(i).longValue() == 0) {
  37.         primeFactor = i;
  38.         n = n.divide(i);
  39.       } else {
  40.         i = i.add(BigInteger.ONE);
  41.       }
  42.     }

  43.     if (primeFactor.compareTo(n) < 0) primeFactor = n;

  44.     return primeFactor;
  45.   }
  46. }
DOWNLOAD

         Created: May 11, 2014
    Last Updated: May 10, 2020
Completed in full by: Michael Yaworski