Java Program for Find largest prime factor of a number
Last Updated :
17 Feb, 2018
Given a positive integer \’n\'( 1 <= n <= 10
15). Find the largest prime factor of a number.
Input: 6
Output: 3
Explanation
Prime factor of 6 are- 2, 3
Largest of them is \'3\'
Input: 15
Output: 5
Java
import java.io.*;
import java.util.*;
class GFG {
static long maxPrimeFactors( long n)
{
long maxPrime = - 1 ;
while (n % 2 == 0 ) {
maxPrime = 2 ;
n >>= 1 ;
}
for ( int i = 3 ; i <= Math.sqrt(n); i += 2 ) {
while (n % i == 0 ) {
maxPrime = i;
n = n / i;
}
}
if (n > 2 )
maxPrime = n;
return maxPrime;
}
public static void main(String[] args)
{
Long n = 15l;
System.out.println(maxPrimeFactors(n));
n = 25698751364526l;
System.out.println(maxPrimeFactors(n));
}
}
|
Output:
5
328513
Time complexity:
Auxiliary space:
Please refer complete article on
Find largest prime factor of a number for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...