ukdev
ukdev

Reputation: 35

I want to take out Last Digit of Huge Number Stored in BigInteger In JAVA

import java.math.BigInteger;
import java.util.Scanner;

public class LastFact
{
    // Returns Factorial of N
    static BigInteger factorial(int N)
    {
        // Initialize result
        BigInteger f = new BigInteger("1"); // Or BigInteger.ONE

        // Multiply f with 2, 3, ...N
        for (int i = 2; i <= N; i++)
            f = f.multiply(BigInteger.valueOf(i));

        return f;
    }

    // Driver method
    public static void main(String args[]) throws Exception
    {
        int N = 300;

        System.out.println(factorial(N));
    }
}

Upvotes: 0

Views: 1797

Answers (4)

hkn
hkn

Reputation: 371

Convert your big integer in to string then take last digit.

public static void main(String args[]) throws Exception
{
    int N = 300;

        String bigNumber = factorial(N).toString();
        String lastNumberStr = bigNumber.charAt(bigNumber.length()-1)+"";
        int lastNumber = Integer.parseInt(lastNumberStr);

        System.out.println(lastNumber);
}

Upvotes: 0

Maksym Kreshchyshyn
Maksym Kreshchyshyn

Reputation: 354

You can write a function:

public byte lastDigit(BigInteger value) {
    String str = String.valueOf(value);
    String digit = str.substring(str.length() - 1, str.length());
    return Byte.valueOf(digit);
}

Upvotes: 0

Deb
Deb

Reputation: 2972

To take the last digit get the remainder of BigInteger when divided by 10

System.out.println(f.remainder(BigInteger.TEN));

Upvotes: 1

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

If you want to remove the last N digits of a BigInteger divide it by 10^N e.g. to remove the last two digits divide by 10^2=100:

BigInteger i = new BigInteger("123456");
BigInteger j = i.divide(BigInteger.valueOf(100)); // j=1234 

To get the reminder that you are removing use the reminder() method instead:

BigInteger i = new BigInteger("123456");
BigInteger j = i.reminder(BigInteger.valueOf(100)); // j=56 

Please note that since you are calculating large factorials you might want to use Stirling's approximation.

Upvotes: 1

Related Questions