Java: Print all prime factors of a given number
Prime Factors of Number
Write a Java program to print all the prime factors of a given number.
Sample Solution:
Java Code:
import java.util.*;
class solution {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.print("Input a number: ");
int n = scan.nextInt();
if (n>0)
{
while (n%2==0)
{
System.out.print(2 + " ");
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
while (n%i == 0)
{
System.out.print(i + " ");
n /= i;
}
}
if (n > 2)
System.out.print(n);
}
}
}
Sample Output:
Input a number: 78 2 3 13
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to calculate e raise to the power x using sum of first n terms of Taylor Series.
Next: Write a Java program to check if a given number is Fibonacci number or not.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics