开发者

Please discussing my Java code to find Factors(It's Correct?) [closed]

This question is unlikely to help any future visitors; it开发者_StackOverflow社区 is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

Do you have another solution for solve Factor problem?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜