Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

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

1 Answer

0 votes
import java.math.BigInteger

/*
    Demonstrates extracting the first N digits from a BigInteger.

    Flow:
    - Build a large BigInteger.
    - Choose how many leading digits we want.
    - Call a helper function that returns those digits.
    - Print the result.
*/
fun main() {

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

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

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

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

/*
    Returns the first N digits of a BigInteger.

    Approach:
    - Convert the BigInteger 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.
*/
fun getLeadingDigits(value: BigInteger, 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) {
        return text
    }

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


/*
run:

First 20 digits: 12345678901234567890

*/

 



answered 1 day ago by avibootz
...