Hello I am working on a Prime Factor program in Java. I need to make some change
ID: 3769236 • Letter: H
Question
Hello I am working on a Prime Factor program in Java. I need to make some changes to my program below!
1. I need to display the orginial input at the end of the factor print out (Ex: if the user enters 40, the output would be 2 2 2 5 40)
2. I need then to print all the factors (Ex: if the user enters 40, the output would be 1 2 4 5 8 10 20 40)
Program so far:
package primenumbers;
import java.io.*;
class PrimeNumbers {
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.print("Enter a Number to Factor: ");
n=Integer.parseInt(br.readLine());
System.out.print("Prime Factors: ");
int i=2;
while(n>1)
{
if(n%i == 0)
{
System.out.print(i+" ");
n=n/i;
}
else
i++;
}
}
}
Please help me make these changes!! My program is finding the prime factors fine, i just need to change how the console prints out the factors!!!
Explanation / Answer
package primenumbers;
import java.io.*;
class PrimeNumbers {
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
System.out.print("Enter a Number to Factor: ");
n=Integer.parseInt(br.readLine());
System.out.print("Prime Factors: ");
int i=2;
int temp = n;
while(temp>1)
{
if(temp%i == 0)
{
System.out.print(i+" ");
temp=temp/i;
}
else
i++;
}
System.out.print(n+" ");
temp = n;
for(i=1;i<=temp;i++)
{
if(temp%i==0)
System.out.print(i+" ");
}
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.