I'm trying to get the prime factors of a given number using java.I was able to write following code.It's returning 2,5,10 for the prime factors of 100 while 10 is not a prime number and also it's returning 2,4,11 for the prime factors of 88 wile 4 is not a prime number.Can any one please explain what is the reason and how to fix it?.
import java.util.ArrayList;
import java.util.Random;
public class PrimeFactors {
public static void main(String[] args) {
Random randomGenarator = new Random();
int number = randomGenarator.nextInt(150);
System.out.println("Prime factors of :" + number);
findPrimeFactors(number);
}
private static void findPrimeFactors(int i) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int n = 2; n <= i; n++) {
if (i % n == 0) {
list.add(n);
i /= n;
}
}
for (int n : list) {
System.out.println(n);
}
}
}
You aren't testing for multiple identical factors in your original number. E.g. when testing
88, you find a2, but you miss the other2s. (The number is now44.) Then you skip to3and don't find it. Then you find4, because4is a factor of44.You need to keep testing a factor until you no longer find it. Replace the
ifwithwhile:This way you'll find all
2s in the factor before anything else. Then when you get to other composite numbers such as4to test, you won't find them.