# Prime Factorization Method: Won't reproduce all Factors every time

• September 30th, 2011, 12:42 AM
Staticity
Prime Factorization Method: Won't reproduce all Factors every time
Code :

``` public ArrayList hasPrimeFactors(int x){ ArrayList list = new ArrayList(); if(isPrime(x)==true){ list.add(x); } for(long i = 2; i<x; i++){ while(x % i == 0){ System.out.println(); list.add(i); x /= i; } } if(list.size() == 0){ list.add("No Prime Factors"); } return list; }```

I suppose the issue arises in the While loop that is nested within the For Loop. I am guessing that the division x /= i; won't produce a remainder of 0 once the number is divided by the modulus again.. If that previous sentence doesn't make sense to you, ignore it. But, could someone guide me or go through this to see what's causing the issue? I've already debugged it, and noticed this trend...

Input: 15
Prime Factors: [3]

Input: 25
Prime Factors: [5, 5]

Input 14:
Prime Factors: [2]

Input 50:
Prime Factors: [2, 5, 5]

Input 8:
Prime Factors: [2, 2, 2]

Here are several different scenarios... Any help would be greatly appreciated.
• September 30th, 2011, 05:16 AM
Mr.777
Re: Prime Factorization Method: Won't reproduce all Factors every time
In case of 14: The reason is first time you enter in the for loop, x's value is 14. So, in while loop, 14%2==0 and it enters and sets the value of x to 7 by your statement x/=i;
And you know 7 has no factors at all except 7 but you are running your loop <x, means 6. So, that is why you are getting only one factor instead of 2.
Note: Store the x value in some temporary variable and assign that temporary variable as a condition to for loop(outer loop).
Hope it helps..