Question

This program basically factors and prints using exponents. It is getting close to the right answer, but it continues looping and doesn't print them on the same line. For example, for 600 it should print 2^3*3*5^2, but continues to print 2^3 (new line) 3^1 (new line) 5^2, repeated.

UPDATE: fixed the repeating problem by fixing the sentinal, now prints 2^3 3^1 5^2, just need t to print correctly now.

import java.util.Scanner;
class Factoring {
    int n;
    void setN(int u) {
        n = u;
    }

    int getN() {
        return n;
    }

    void factorize() {
        int cnt;

        for (int i = 2; i <= n; i++) {
            cnt = 0;
            while (n%i == 0) {
                cnt++;
                n /= i;
            }
            if (cnt == 0)
                continue;
            System.out.println(i + "^" + cnt);
        }
    }
}

public class Hw10 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Factoring myF = new Factoring();

        int u;

        System.out.print("Enter a number(1 or less to stop)");
        u = in.nextInt();
        while (u > 1) {
            myF.setN(u);
            myF.factorize();

            System.out.print("Enter a number(1 or less to stop)");
            u = in.nextInt();
        }
        System.out.print("bye");
    }
}
Was it helpful?

Solution

You need a flag inside the loop to determine if it's the first factor eg

    int cnt;
    boolean isFirstFactor = true;

    for (int i = 2; i <= n; i++) {
        cnt = 0;
        while (n%i == 0) {
            cnt++;
            n /= i;
        }
        if (cnt == 0)
            continue;
        if (isFirstFactor)
            isFirstFactor = false;
        else
            System.out.print(" * ");
        System.out.print(i + "^" + cnt);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top