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

# Need help with BigInteger

Ranch Hand
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...

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

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

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.

Marshal
Posts: 57444
175
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
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.

Rancher
Posts: 42975
76
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.

 The government thinks you are too stupid to make your own lightbulb choices. But this tiny ad thinks you are smart: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS