×

Java Programs

Java Practice

Java program to find out prime factors of given number

This java program will read an integer numbers and find its prime factors, for example there is a number 60, its primer factors will be 2, 3 and 5 (that are not divisible by any other number).

package com.includehelp;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * Program to find out prime factors of given number
 * @author includehelp
 */
public class PrimeFactors {
    
    /**
     * method to find prime factor for supplied number
     * @param number
     * @return 
     */
    static String getPrimeFactors(long number){
        Set<Integer> setPrimeFactors = new HashSet<>();  //set not Allowd Duplicate element
        for (int i = 2; i<= number; i++) {
            if (number % i == 0) {
                setPrimeFactors.add(i); // Add prime factor in Array List
                number = number/ i;
                i--;
                
            }
        }
        return setPrimeFactors.toString();
    }
    
    public static void main(String[] args) {
        Scanner sc  =   new Scanner(System.in);
        System.out.print("Enter Number  : ");
        int number =   sc.nextInt();
        
        System.out.println("Prime Factors of "+number+" is : "+getPrimeFactors(number));
    }
}

Output

Enter Number  : 60
Prime Factors of 60 is : [2, 3, 5]

Enter Number  : 1000
Prime Factors of 1000 is : [2, 5]

Java Most Popular & Searched Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.