Please discussing my Java code to find Factors(It's Correct?) [closed]
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.
精彩评论