Hi guys , is me again !

I get stucked on this question

Write a program that read an integer and display its smallest prime factors in ascending order. For example, if the input is 60, the output should be 2,3,5...
I came out with below code, but I get 2 2 3 5.How to have only one 2 ?

package chapter4;

import java.util.Scanner;

public class Exercise4_16 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        Exercise4_16 exe = new Exercise4_16();
        int value = input.nextInt();
        exe.primeFactors(value);
    }

    public void primeFactors(int value) {
        while (value % 2 == 0) {
            System.out.print(2 + " ");
            value = value / 2;
        }

        for (int i = 3; i <= Math.sqrt(value); i = i + 2) {
            while (value % i == 0) {
                System.out.print(i + " ");
                value /= i;
            }
        }

        if (value >= 2) {
            System.out.print(value);
        }
    }
}

Recommended Answers

All 2 Replies

I should remove line 17.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.