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

1 Answer

0 votes
/*
    Demonstrates extracting the first N digits from a BigInt.

    Flow:
    - Build a large BigInt.
    - Choose how many leading digits we want.
    - Call a helper function that returns those digits.
    - Print the result.
*/
object LeadingDigitsDemo {

  def main(args: Array[String]): Unit = {

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

    // Number of digits we want from the front.
    val digitsRequested = 18

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

    // Display the result.
    println(s"First $digitsRequested digits: $leading")
  }

  /*
      Returns the first N digits of a BigInt.

      Approach:
      - Convert the BigInt to a string once.
        This avoids manual digit extraction and leverages efficient built‑in conversion.
      - If the number has fewer digits than requested, return the whole string.
      - Otherwise, slice the string using substring.
  */
  def getLeadingDigits(value: BigInt, count: Int): String = {

    // Convert to text representation.
    val text = value.toString

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



/*
run:

First 18 digits: 987654321098765432

*/

 



answered Aug 14 by avibootz
edited Aug 14 by avibootz
...