| Author |
Having trouble writing a method that factors negative numbers.
|
Angela Li
Greenhorn
Joined: Nov 04, 2011
Posts: 12
|
|
I am trying to write a method that returns the list of factors when I input an integer.
When I run it using my main I get an error message:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at QuadraticEqn.getIntegerFactors(QuadraticEqn.java:51)
at QuadraticEqn.main(QuadraticEqn.java:9)
What am I doing wrong?
|
 |
Persio Berberian
Greenhorn
Joined: Aug 27, 2011
Posts: 9
|
|
|
Are you inputing a negative number?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Angela Li wrote:
i starts at 1, then becomes 0. That will cause n % i to fail. Make i start at -1 instead.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32639
|
|
|
Set a boolean negative flag, take the absolute value of the number, factorise it, and if (negative) add -1 to the list of factors.
|
 |
Angela Li
Greenhorn
Joined: Nov 04, 2011
Posts: 12
|
|
|
Thanks Rob, I didn't realize that.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
You're welcome. But Campbell does have a point - my code will miss one or two factors. His approach is much better.
|
 |
 |
|
|
subject: Having trouble writing a method that factors negative numbers.
|
|
|