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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework