Project Euler : Problem 3 - Largest prime factor

2 minute read

Problem Statement : Largest prime factor

Problem 3 : The prime factors of are and . What is the largest prime factor of the number ?

Concept and Theory

The main idea behind this problem is to understand the basic factoring concept, i.e “any number, , can have at-most one prime factor bigger than its , unless the number itself is prime”. Just like sieving in Sieve of Eratosthenes we do our computations.

  • Since is the only special case, only even prime number, we will handle its case separately and keep updating our .
  • After handling ’s special case, and we update it in increment of as we only care about odd numbers(because they are the only possible solution).
  • As a last step, if after looping over we are still left with some number we will simply make that number our answer. Why ? Because that will be the only one prime bigger than .

Code

/**
 * A function to calculate the largest prime factor of given number
 *
 * @param num
 *            : given number
 * @return largest prime factor of given number
 */
public static long largestPrimeFactor(long num) {

  long searchingRangeMaxNum = (long) Math.sqrt(num);
  long currentLargestFactor = 2;
  long largestFactor = 1;

  if (num % currentLargestFactor == 0) {
    largestFactor = currentLargestFactor;
    num /= currentLargestFactor;
    while (num % currentLargestFactor == 0) {
      num /= currentLargestFactor;
    }
  }

  if (num == 1) {
    return largestFactor;
  }

  currentLargestFactor = 3;

  while (currentLargestFactor <= searchingRangeMaxNum) {
    if (num % currentLargestFactor == 0) {
      while (num % currentLargestFactor == 0) {
        num = num / currentLargestFactor;
      }
      largestFactor = currentLargestFactor;
    }
    currentLargestFactor += 2;
  }
  if (num > 1) {
    largestFactor = num;
  }
  return largestFactor;
}

Test Your Skills

Wanna try a harder version of the above problem ? Check this HackerRank problem.

Solution

The solution will remain same as above method , you just need to call it for each test case.

References and Further Readings

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...