Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Math Exercises: Print all prime factors of a given number

Java Math Exercises: Exercise-26 with Solution

Write a Java program to print all 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.

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.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe