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
*/