# How to find prime factors of a number in java

In this post, we will see how to find prime factors of a number in java.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
The prime factors of a number are all of the prime numbers that will exactly divide the given number.
For example-
Prime factor of 15 = 3,5
Prime factor of 48=2,2,2,2,3Lets create java program for it:

Run above program and you will get following output:

You must be wondering we are not checking whether loop variable i is prime or not But you don’t need to do this because in any loop, number has been already divided by 2 to i-1 so i can only be divisor if it is prime.

#### More optimized solution:

Change above primeFactors function to below function

This is based on the fact that in above for loop,divisor can not be greater than n/i.

Please go through java interview programs for more such programs.

Subscribe to Awesome Java Content.

#### One Response

1. ankur gupta November 5, 2014