-1

Do you have another solution for solve Factor problem?

fronthem
  • 4,011
  • 8
  • 34
  • 55
  • 3
    If this is your homework, you should add the homework tag to the question. – nfechner Jul 21 '11 at 10:39
  • no i using it to solves problem but i'll check it's correct. – fronthem Jul 21 '11 at 10:41
  • 1
    No, it doesn't work: it thinks 35 is a prime number. This is almost a duplicate of your previous question (http://stackoverflow.com/questions/6773462/which-is-the-best-algorithm-for-find-factors-implements-by-java), it would be better if you edited that rather than posting a new question. – OpenSauce Jul 21 '11 at 10:58
  • 1
    Doing %3==0 does not prove something is odd – Landric Jul 21 '11 at 11:06
  • number can be odd and prime in same time. – fronthem Jul 21 '11 at 11:11
  • Yes, but your method of checking if a number is odd is broken - not all odd numbers are divisible by 3. Case in point, 35. – Landric Jul 21 '11 at 11:16
  • Try your program with an input of 35. Does it do what you expect? – OpenSauce Jul 21 '11 at 11:29
  • @Landric //odd number(not prime) – fronthem Jul 21 '11 at 12:36
  • 1
    @1eftHer0: interesting approach to bugfixing ; ). Now, does it do what you expect for an input of 49? This could go on for some time... I'm beginning to suspect we're being trolled... – OpenSauce Jul 21 '11 at 13:01
  • @OpenSauce i think this solution have many bug fixing by (n%3 == 0 || n%5 == 0 || n%7 == 0) best way to solve this problem is random all digit. yes easyway. – fronthem Jul 21 '11 at 13:09
  • bug on this program it from i try to use prime but prime is really hard to solve it. – fronthem Jul 21 '11 at 13:12

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
  • 15,344
  • 1
  • 24
  • 38
  • +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