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();
    }
    
}

in factorize method, in if boolean expression u have written
div % number instead of number % div.

Priya,

Thank you very much!

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.