How to get the first N digits of a BigInteger in Java

1 Answer

0 votes
import java.math.BigInteger;

public class BigIntegerLeadingDigits {

    /**
        Program entry point:
        Demonstrates extracting the first N digits from a BigInteger.

        The flow:
        - Build a large BigInteger.
        - Choose how many leading digits we want.
        - Call a dedicated function that returns those digits.
        - Print the result.
    */
    public static void main(String[] args) {

        // A large BigInteger for demonstration.
        // In real applications this might come from arbitrary‑precision math,
        // cryptographic operations, or large numeric computations.
        BigInteger bigValue = new BigInteger("9876543210987654321098765432109876543210");

        // Number of digits we want from the front.
        int digitsRequested = 15;

        // Extract the first N digits using a clear helper function.
        String leading = getLeadingDigits(bigValue, digitsRequested);

        // Display the result.
        System.out.println("First " + digitsRequested + " digits: " + leading);
    }

    /**
        Returns the first N digits of a BigInteger.

        Approach:
        - Convert the BigInteger to a string once.
          BigInteger already stores its magnitude efficiently, so this conversion
          is fast and avoids unnecessary manual digit extraction.
        - If the number has fewer digits than requested, return the whole string.
        - Otherwise, slice the string using substring.
    */
    public static String getLeadingDigits(BigInteger value, int count) {

        // Convert to text representation.
        String text = value.toString();

        // If the caller requests more digits than available,
        // simply return the entire number.
        if (count >= text.length()) {
            return text;
        }

        // Return the first N characters.
        return text.substring(0, count);
    }
}


/*
run:

First 15 digits: 987654321098765

*/

 



answered Aug 13 by avibootz
...