Java Program for Find largest prime factor of a number.

Below program will find largest prime factor of a number.

package testjava.controlflow;

public class LargestPrimeFactor
{
	public void largestPrimeFactor(long number)
	{
		int i;
		long originalNumber = number;
		
		for(i = 2; i <= number; i++)
		{
			if(number % i == 0)
			{
				number = number / i;
				i--;
			}
		}
		System.out.println("Largest Prime Factor of "+originalNumber+" is: "+i);	
	}
	
	public static void main(String args[])
	{
		LargestPrimeFactor lpf = new LargestPrimeFactor();
		
		lpf.largestPrimeFactor(6);
		lpf.largestPrimeFactor(21);
		lpf.largestPrimeFactor(45);
		lpf.largestPrimeFactor(217);
	}
}

OUTPUT

Largest Prime Factor of 6 is: 3
Largest Prime Factor of 21 is: 7
Largest Prime Factor of 45 is: 5
Largest Prime Factor of 217 is: 31