Javatpoint Logo
Javatpoint Logo

Prime Factor Program in Java

Prime factorization is a fundamental concept in number theory that involves breaking down a composite number into its smallest prime factors. This process is invaluable in various fields of mathematics and computer science, including cryptography and number theory. In this section, we will explore how to create a prime factor program in Java.

Before delving into the Java code, it's crucial to grasp what prime factors are.

Prime Factors

Prime factors are the prime numbers that, multiplied together, yield a given composite number. For example, the prime factors of 12 are 2 and 3 because 2 * 2 * 3 = 12.


To develop a prime factor program in Java, we will use a straightforward algorithm:

  • Initialize a variable to hold the number for which we want to find the prime factors.
  • Start a loop that iterates from 2 (the smallest prime number) up to the given number.
  • At each iteration, check if the current number is a factor of the given number.
  • If it is, check if it's a prime number.
  • If it's a prime factor, divide the given number by it and print the factor.
  • Continue until the given number becomes 1.

File Name:


Prime factors of 56 are: 2 2 2 7


  • Run a while loop that will terminate when the number is not divisible by two,
  • So, inside that loop print("2"), and divide the number by 2 in each iteration.
  • After this, n will be odd number. Now start a loop from i = 3 to square root of n.
  • Run a while loop that terminate when i is not divisible by n,
  • Inside loop print i and divide n by i, increment i by 2 and continue.
  • If n is a prime number and is greater than 2, then n will not become 1 by above two steps.
  • So print n if it is greater than 2.

Let's implement the above steps in a Java program.

File Name:


2 3 3 5 


Developing a prime factor program in Java involves breaking down a number into its prime components. It not only provides insight into the number's mathematical makeup but also has practical applications in various fields. Understanding prime factors is essential for more complex mathematical operations and algorithms. The code provided serves as a starting point for further exploration and refinement, offering a solid foundation for more advanced programs.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA