programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Why is my multiplication going negative?

Greg Zobel
Greenhorn
Posts: 23
1
Howdy! folks,

I'm working on the problem found here: http://www.codeabbey.com/index/task_view/modular-calculator

How is my answer going negative when the only operations are addition and multiplication?

My code is

testData is

Results are

...

Henry Wong
author
Sheriff
Posts: 23295
125
• 1
Greg Zobel wrote:
How is my answer going negative when the only operations are addition and multiplication?

A long variable is a 64 bit variable, and the largest number that it can hold (supporting twos complement format) is 9223372036854775807. If you go larger than that, the variable will overflow... ie. adding one to the largest possible number will yield the smallest (largest negative) possible number.

Henry

A.J. Côté
Ranch Hand
Posts: 417
• 1
Henry Wong wrote:
Greg Zobel wrote:
How is my answer going negative when the only operations are addition and multiplication?

A long variable is a 64 bit variable, and the largest number that it can hold (supporting twos complement format) is 9223372036854775807. If you go larger than that, the variable will overflow... ie. adding one to the largest possible number will yield the smallest (largest negative) possible number.

Henry

Additionally, you may have a look at the class java.lang.BigInteger which has no theoretical limit on the size of the integer it can represent. Similarly, java.math.BigDecimal is used in accounting software because it has no theoretical limit on the precision as well as on size while double and float have limits on the precision that cause the books not to balance in some cases.

Greg Zobel
Greenhorn
Posts: 23
1
So this is how I made it work:

Henry Wong
author
Sheriff
Posts: 23295
125
Greg Zobel wrote:So this is how I made it work:

Thanks for returning to report on your solution ... you earned a cow.

Henry

Greg Zobel
Greenhorn
Posts: 23
1
Henry Wong wrote:
Greg Zobel wrote:So this is how I made it work:

Thanks for returning to report on your solution ... you earned a cow.

Henry

Thank you!