Java Program to find the largest prime factor
A number which is divided by itself and 1 is called Prime number. Prime factors consist of prime numbers which are the multiplied to generate the original number.
Eg:
45 =3X3X5
Largest prime factor is5.
Let us implement this concept in java.
Steps to follow:
- A public class LargestPrimeFactorEg is generated with constructor LargestPrimeFactorEg().
 - The constructor gets an input as the number.
 - Two long variables are declared with initial values.
 - One is for largestfactor(largeFactor) and another one is for divisor(div).
 - A while loop is created with the condition the number is greater than one.
 - Using % operator,the remainder is checked with zero. If so, largefactor is set to divisor value.
 - The no value is divided by divisor and stored it in no.
 - Again, in the another while loop,no % divisor value is equal to zero, no is divided by divisor and it is assigned to no.
 - Increment the divisor value by 1.
 - Repeat this process until the condition fails.
 - Finally return the largest factor value to the main function.
 - In the main() function, read the input as no from the user.
 - Call the largestPrimeFactorEg() function.
 - Get the returned value from the function and print it to the output screen.
 
Program:
import java.util.Scanner;
//public class with constructor
public class LargestPrimeFactorEg {
    public static long
largestPrimeFactorEg(long no) {
        long
largeFactor = 1;
        long div = 2;
        while (no >
1) {
            if (no %
div == 0) {
               
largeFactor = div;
                no /=
div;
                while
(no % div == 0) {
                    no
/= div;
                }
            }
            div++;
        }
        return
largeFactor;
    }
//main() function
    public static void
main(String[] args) {
        Scanner myObj1
= new Scanner(System.in); 
       
System.out.println("Enter the number"); 
        long no =
myObj1.nextLong();
       
System.out.println("The Largest prime factor of the given number:
" + largestPrimeFactorEg(no));
    }
}
Output:
C:\raji\blog>javac LargestPrimeFactorEg.java
C:\raji\blog>java LargestPrimeFactorEg
Enter the number
56
The Largest prime factor of the given number: 7
C:\raji\blog>java LargestPrimeFactorEg
Enter the number
765
The Largest prime factor of the given number: 17
This is the java Program to find the largest prime
factor. Keep coding!!!!
Comments
Post a Comment