w3resource

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:

Flowchart: Print all prime factors of a given number.

For more Practice: Solve these Related Problems:

  • Write a Java program to recursively factorize a number into its prime factors and print each factor.
  • Write a Java program to generate the prime factors of a number using trial division and count their frequencies.
  • Write a Java program to factorize a number recursively and then compute the product of its unique prime factors.
  • Write a Java program to print all prime factors of a number and then sort them in ascending order.

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.



Follow us on Facebook and Twitter for latest update.