aspose file tools
The moose likes Beginning Java and the fly likes Having trouble writing a method that factors negative numbers. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Having trouble writing a method that factors negative numbers. " Watch "Having trouble writing a method that factors negative numbers. " New topic
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
    
    4
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.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Having trouble writing a method that factors negative numbers.
 
Similar Threads
Prime Factor Program
Power Strings
Practical Number?
Recursion-Prime factors
Error states: This method must return a result of type int