Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes Need help with BigInteger Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need help with BigInteger" Watch "Need help with BigInteger" New topic

Need help with BigInteger

Nathan Leniz
Ranch Hand

Joined: Nov 26, 2006
Posts: 132
Having a bit of a problem working on problem 16 on the project euler site.

Given BigInteger base = BigInteger.valueOf(2); for both examples...

<pre name="code" class="core">
BigInteger total = BigInteger.ZERO;
total = base.pow(1000);

gives different output than
<pre name="code" class="core">
BigInteger total = BigInteger.ZERO;
for (int i = 0; i < 1000; i++)
total = total.multiply(base);

I'm really at a loss. Perhaps it's late and I'm not thinking clearly, but later methods to sum up the individual digits of total aren't giving me the right answer.

The very existence of flamethrowers proves that at some time, some where, some place, someone once said to themselves "I'd really like to set those people on fire over there, but I just can't get close enough".
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 36468
It shouldn't be at all difficult to count the digits of your result starting from BigInteger.ZERO. There will be one "0".

Try BigInteger.ONE

And please supply a link using the URL button so we can find your puzzles more quickly.
Nathan Leniz
Ranch Hand

Joined: Nov 26, 2006
Posts: 132
Sorry, getting late. Rather than using BigInteger.Zero in the second loop, I used BigInteger.valueOf(2).

And I found out what it's doing, the second way is actually taking it to the 1001st power. Still no luck on the answer.

Oh, here is the link. Project Euler problem 16.
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 39543
Just as an aside, I've done a fair number of the Project Euler problems in Java, and I've always considered using the BigInteger class as a bit of cheating. It's more interesting to come up with alternative solutions, IMO. The whole point is to learn about algorithms and math, after all.

Ping & DNS - updated with new look and Ping home screen widget
I agree. Here's the link:
subject: Need help with BigInteger
Similar Threads
JBoss EAR structure
Using ID of link as Parameter
Illegal Escape Character
StringBuffer / StringBuilder methods
Conditional (Ternary) Operator (?:)