Q:

Java program to find out prime factors of given number

belongs to collection: Java Most Popular & Searched Programs

0

Java program to find out prime factors of given number

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to check whether given number is Arms... >>
<< Java program to print all Java properties...