• Post Reply Bookmark Topic Watch Topic
  • New Topic

Having trouble writing a method that factors negative numbers.  RSS feed

 
Angela Li
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you inputing a negative number?
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angela Li wrote:

i starts at 1, then becomes 0. That will cause n % i to fail. Make i start at -1 instead.
 
Campbell Ritchie
Marshal
Posts: 56522
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob, I didn't realize that.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. But Campbell does have a point - my code will miss one or two factors. His approach is much better.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!