0

Hello. I am having a problem generating the prime numbers from user input. The problem lies in the factorize method. I think I am really close to getting this to work, but I cannot seem to figure out the last detail that I need to include. Can anyone help? Thank you.

import java.util.*; 

public class PrimeFactors {     
    
    public PrimeFactors() {        
        int number = 0;        
        while(number != -1) {            
            number = readIntFromUser();            
            if(isPrime(number)) {               
                System.out.println(number+" is a prime!");
            }            
            else {
                System.out.println(number+"'s prime factors are: "+factorize(number));
            } 
        }
        System.out.println("Bye!");
    }
    public Set<Integer> factorize(int number) {
        Set<Integer> primeFactors = new TreeSet<Integer>();

        
        int div = 2; 
        while (number > 1)  //WHILE number is more than one 
        {
            if ( div % number ==0) 
            {
                primeFactors.add(new Integer(div));
                number = number / div;
            }
            else
                div++; //increase 'div' by one
            
           }
          return primeFactors;
         
    }
       
    public boolean isPrime(int number) {
        int root = (int)Math.sqrt(number);
        for(int i = 2; i <= root; i++) {
            if(number%i == 0) {
                return false;
            }
        }
        return true;
    }
    public int readIntFromUser() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter a number, -1 to terminate:" );
        return scanner.nextInt();
    }
    public static void main(String[] args) {
        new PrimeFactors();
    }
    
}
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by AllenB
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.