A Prime Factors of a given number is that any prime number other than 1 and itself that exactly divides the given number. For example, the prime factors of 60 is 2, 3, 5
Examples
The following table provides few examples of prime factors of a number.
Number
Prime Factors
55
5, 11
100
2, 5
186
2, 3, 31
Find Prime Factor
In the following example, we will find all the Prime factors of the given number (186).
Example
Java Compiler
public class myClass
{
public static void main(String[] args)
{
int num =186;
int i, j;
int count =0;
int flag =0;
System.out.format("Prime factor of %d:\n", num);
for(i=2; i<num; i++)
{
// check for divisibilityif(num % i ==0)
{
count =0;
// check for prime numberfor(j=1; j<=i; j++)
{
if(i % j ==0)
count++;
}
if(count ==2)
{
flag =1;
System.out.print(i +" ");
}
}
}
if(flag ==0)
System.out.format("There is no Prime factor for %d ", num);
}
}
Output
Prime factor of 186:
2 3 31
Find Prime Factor of any Given Number
In the following example, we will find a prime factors of any given number.
Example
Java Compiler
import java.util.Scanner;
public class myClass
{
public static void main(String[] args)
{
Scanner reader =new Scanner(System.in);
System.out.print("Enter a (int) Number: ");
int num = reader.nextInt();
int i, j;
int count =0;
int flag =0;
System.out.format("\nPrime factors of %d:\n", num);
for(i=2; i<num; i++)
{
// check for divisibilityif(num % i ==0)
{
count =0;
// check for prime numberfor(j=1; j<=i; j++)
{
if(i % j ==0)
count++;
}
if(count ==2)
{
flag =1;
System.out.print(i +" ");
}
}
}
if(flag ==0)
System.out.format("There is no Prime factor for %d ", num);
}
}
Output
Enter a (int) Number: 45
Prime factors of 45:
3 5
Reminder
Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.
We are working to cover every Single Concept in Java.