Josh Landweber
Josh Landweber

Reputation: 23

What do I do when a Long isn't long enough (Java)?

So, I'm working through the bottom of Project Euler. There are a lot of great problems there (most of which are way above my level). But I very quickly came across a major problem:

Java will not do huge numbers.

Now, if I had the ability to make fast programs taking alternative routes, this would not be a problem for me. Unfortunately, I am not that person.

Take, for example, Problem 20. It call to find the digit sum of 100! I wasn't even writing for the digit parsing, but just my code to find the factorial failed.

long onehfact = 1;
for(int i = 1; i <= 100; i++){
    onehfact = onehfact * i;
    System.out.println(onehfact);
}

This worked for about 20 sequences, but started giving random-ish 19 digit numbers. By 75 sequences, it was just giving me zero.

100! is definitely not zero.

I need a way to have incredibly large numbers, and scientific notation will not work for my purposes. Is there a large variable type that I could use, that can hold numbers as large as 100-150 digits? Is there any other solution that would have the same result?

Upvotes: 0

Views: 1602

Answers (2)

La-comadreja
La-comadreja

Reputation: 5755

There is a class called BigInteger that will allow you to handle and perform operations on numbers of any size. It will allocate a variable amount of memory for the digits.

Here is the documentation. The class is in the java.math package:

http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

I worked through some problems in Project Euler in Java, too. For some of the other problems you are dealing with large non-integer numbers and you need the related class java.math.BigDecimal:

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

Upvotes: 3

Amir Afghani
Amir Afghani

Reputation: 38541

You can use BigInteger to satisfy your requirement.

BigInteger onehfact = BigInteger.valueOf(1L);
for(long i = 1; i <= 100; i++){
    onehfact = onehfact.multiply(i);    
    System.out.println(onehfact);
}

Upvotes: 1

Related Questions