-3

Good evening,

I'm a beginner in java and I was assigned to code a program to decompose prime number. This is what I've got so far.

package introductionProgramming;

import javax.swing.JOptionPane;

public class Primes {
                public static void main(String[] args) {
                int primo;

    primo = Integer.parseInt(JOptionPane.showInputDialog("Inform prime number: "));

        while (prime % 2 == 0) {
            prime = prime / 2;
        }
        while (prime % 3 == 0) {
            prime = prime / 3;
        }
        while (prime % 5 == 0) {
            prime = prime / 5;
        }

        JOptionPane.showMessageDialog(null, prime);
                }
    }

So the decomposition part seems to work but I need the output, if entered the number 180, to look similar to this:

180  2
90   2
45   3
15   3
5    5
1

I have no clue how to do it.

1 Answers1

1

To send the calcultation as a whole to the output, you will need to gather all results and send it as a whole. To achieve this, when finding each result, you will add the appropriate text to a StringBuffer object, that will gather the results where ultimately it will be displayed. Below is an example of your code.

public class Primes {
    public static void main(String[] args) {


    int prime = Integer.parseInt(JOptionPane.showInputDialog("Inform prime number: "));
    StringBuffer resultsBuffer = new StringBuffer();

    while (prime % 2 == 0) {
        resultsBuffer.append(prime+" "+2+"\n");
        prime = prime / 2;

    }
    while (prime % 3 == 0) {
        resultsBuffer.append(prime+" "+3+"\n");
        prime = prime / 3;

    }
    while (prime % 5 == 0) {
        resultsBuffer.append(prime+" "+5+"\n");
        prime = prime / 5;

    }

    resultsBuffer.append(prime+" "+1+"\n");



    JOptionPane.showMessageDialog(null, resultsBuffer);
    }
}
Rami Del Toro
  • 1,130
  • 9
  • 24