Write a Java application that prints the prime factorization of an input. Print
ID: 674932 • Letter: W
Question
Write a Java application that prints the prime factorization of an input. Print "is prime" message if input is prime; otherwise, print the prime factorization of the input.
Prompt the user to enter a positive integer and read it from the standard input stream. Print an error message if the user does not enter a positive integer. The input must be read using the System.in object directly.
The following code snippet reads the standard input stream one character at a time until a newline encountered. Each entered character is printed to the standard output stream.
Example Program Output
The inputs were 42, 37, 314, 3993, 101, 31046
Explanation / Answer
# include <iostream>
#include<math.h>
using namespace std;
void factors(int n)
{
int temp = n;
cout<<"1, ";
while (n%2 == 0)
{
cout<<2<<", ";
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
cout<<i<<", ";
n = n/i;
}
}
}
int main()
{
int n;
cin>>n;
factors(n);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.