0

Do you have another solution for solve Factor problem?

fronthem
  • 3,855
  • 6
  • 31
  • 52

1 Answers1

5

A few comments. Firstly, as @OpenSource pointed out, this code does not work correctly. You should probably simplify your approach by forgetting primes at the top level. Primes do not need to be treated separately.

Some comments on specific lines of code:

ArrayList<Integer> list = new ArrayList<Integer>();

At this point you know that there are two factors, 1 and n. Why not add them immediately to the list?

if(i > n/2) break; //optimize

Why do you recalculate n/2 if n hasn't changed since last time?

if(n % i == 0) list.add(new Integer(i));

If i is a factor then (n / i) is also a factor. Every time you get n % i == 0 you have found two factors.

}else if(n%3 == 0 && n%2 != 0 && n != 3 && n != 1){   //odd number

This doesn't work and takes far too much effort to do it. You have already looked at even numbers, what is left must be odd.

}else{ //prime

No, what is left isn't prime. And there is one even prime number as well.

for(int a:list){
    System.out.println(a);
}

You might want to sort list first, before printing.

rossum
  • 14,876
  • 1
  • 21
  • 36
  • +1 for making the effort. One thing I spotted: beware of the case `i == n / i` (don't add the same factor to the list twice). – OpenSauce Jul 21 '11 at 11:51