Java Program to Perform the Unique Factorization of a Given Number

«
»
This is the java program to find out all the prime factors of a given number. Any number can be represented as a product of its prime numbers. User have to input the number and output is the list of prime factors.

Here is the source code of the Java Program to perform the unique factorization of a given number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is sample program to find out all the prime factors of a given number
  2. import java.util.HashSet;
  3. import java.util.Scanner;
  4. import java.util.Set;
  5.  
  6. public class Unique_Prime_Factors 
  7. {
  8.     static Set primeFactors(long number) 
  9.     {
  10.         long copy = number, i;
  11. 	Set primeFactor = new HashSet<>();
  12.         for (i = 2; i <= copy; i++) 
  13.         {
  14.             if (copy % i == 0) 
  15.             {
  16.                 primeFactor.add(i);
  17.                 copy /= i;
  18.                 i--;
  19.             }
  20.         }
  21.         return primeFactor;
  22.     }
  23.  
  24.     public static void main(String args[]) 
  25.     {
  26.         Scanner input = new Scanner(System.in);
  27.         long n;
  28.         System.out.println("Enter the number: ");
  29.         n = input.nextLong();
  30.         System.out.println("The Prime Factors of " + n + " is: "
  31. 				+ primeFactors(n));
  32.     }
  33. }

Output:

advertisement
$ javac Unique_Prime_Factors.java
$ java Unique_Prime_Factors
Enter the number: 
35
The Prime Factors of 35 is: [5, 7]
 
Enter the number: 
1225
The Prime Factors of 1225 is: [5, 7]

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.