ch1maera
ch1maera

Reputation: 1447

Prime Factorization Program in Java Using Loops

I have to write a program that takes a number from the user and then displays the prime factors of the number. This is the program I have so far:

public static void main(String[] args) {
        int a = getInt("Give a number: ");
        int i = 0;

        System.out.println("Your prime factors are: " + primeFactorization(a, i));

    }

    public static int getInt(String prompt) {
        int input;

        System.out.print(prompt);
        input = console.nextInt();

        return input;
    }

    public static int primeFactorization(int a, int i) {
        for (i = 2; i <= a ; i++) {
            while (a % i == 0) {
                a /= i;
            }
        }
        return i;
    }

}

I can't figure out how to get it to print out the list of numbers. Any help is appreciated.

Upvotes: 1

Views: 1326

Answers (2)

Bimde
Bimde

Reputation: 742

While @Paul Boddington's answer is better in most cases (i.e. if you are using the values afterwards), for a simple program like yours, you could add all of the factors to a string and return the string. For example:

public static String primeFactorization(int a) {
    String factors = "";
    for (int i = 2; i <= a ; i++) {
        while (a % i == 0) {
            factors += i + " ";
            a /= i;
        }
    }
    return factors;
}

Upvotes: 1

Paul Boddington
Paul Boddington

Reputation: 37645

You should return a List<Integer> not a single int, and there is no point in i being an argument. A correct method is

public static List<Integer> primeFactorization(int a) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 2; i <= a ; i++) {
        while (a % i == 0) {
            list.add(i);
            a /= i;
        }
    }
    return list;
}

Upvotes: 3

Related Questions