Tuesday, August 18, 2009

Prime Factors Java Program

Hello all of you. Today at Java Code Online, I would be discussing the Java Code for finding all the prime factors of an entered number.

Prime Factors are those numbers which are factors of the entered number, and also are Prime in nature. For being a factor, the number needs to divide completely the entered number. For example, f I say that the user entered 20, then the factors of this number are 1 2 4 5 10 and 20, but when we say about Prime Factors then out of these only 2 and 5 are prime, so 2 and 5 are the Prime factors of the number 20 which is entered by the user.

The complete Java code is given below:-

////////////////////////////////////////

package developer;

import java.util.Scanner;

public class PrimeFactor {

static int primeCheck = 1;

public static void main(String[] args) {
System.out.println("Enter a number whose Prime factors are desired: ");
Scanner numS = new Scanner(System.in);
int numPriFac = 0;
if(numS.hasNextInt())
{
numPriFac = numS.nextInt();
}

System.out.println("All the Prime Factors of the entered number are:-");

for(int tap = 1; tap <= numPriFac; tap++)
{
if(numPriFac%tap == 0)
{
for(int primeTest = 2; primeTest < tap; primeTest++)
{
if(tap%primeTest == 0)
{
primeCheck = 1;
break;
}
else
{
primeCheck = 0;
}
}
if(primeCheck == 0 || tap == 2)
{
System.out.print(tap+ " ");
}
}
}
}
}

///////////////////////////////////////////

I hope the code was helpful to all of you. Java Code Online keeps on discussing various Java codes, so keep checking for new updates.

Related Links:-
Prime Number program in Java
Largest Prime number Java Program
Smallest Prime Number Java Program
Prime Number Series Java Program

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.