Java Program to find largest prime factor of a number


Following is the Java code to find the largest prime factor of a number −

Example

 Live Demo

import java.io.*;
import java.util.*;
public class Demo{
   static long maxPrimeFactors( long val){
      long max_prime = -1;
      while (val % 2 == 0) {
         max_prime = 2;
         val >>= 1;
      }
      for (int i = 3; i <= Math.sqrt(val); i += 2){
         while (val % i == 0){
            max_prime = i;
            val = val / i;
         }
      }
      if (val > 2)
      max_prime = val;
      return max_prime;
   }
   public static void main(String[] args){
      int val = 148592;
      System.out.println("The largest prime factor of 148592 is ");
      System.out.println(maxPrimeFactors(val));
      val = 890654;
      System.out.println("The largest prime factor of 890654 is ");
      System.out.println(maxPrimeFactors(val));
   }
}

Output

The largest prime factor of 148592 is
251
The largest prime factor of 890654 is
4591

A class named Demo contains a static function that tales a value, and a ‘while’ condition is defined, which checks whether the value modulus 2 is 0. If it is 0, then, a variable (max_prime) is assigned the value 2. Otherwise, it is right bit shifted by 1. Again, a ‘for’ loop is iterated over elements from 3 to square root of the value, and incremented by 2 after every iteration.

Now, a ‘while’ loop checks if the value modulus iterator is 0. If yes, a variable (max_prime) is assigned the value that is currently being iterated. The value is divided by the iterated value. If this value is greater than 2, then this value (max_prime) is assigned to a variable named max_prime. This is returned. In the main function, an integer value is defined and the largest prime factor is found out by calling the function with the specific argument.

Updated on: 04-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements