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

1 Answer

0 votes
use num_bigint::BigInt;
use num_traits::Num;

// Extracts the first `n` digits from a BigInt.
// The number is converted to a decimal string once,
// which is efficient and avoids repeated arithmetic operations.
fn first_n_digits(value: &BigInt, n: usize) -> String {
    // Convert the BigInt to a base‑10 string.
    // This gives direct access to its digits.
    let s = value.to_string();

    // If n is larger than the number of digits, return the whole string.
    if n >= s.len() {
        return s;
    }

    // Return the first n characters (digits).
    s[..n].to_owned()
}

fn main() {
    // Construct a large BigInt using `from_str_radix`,
    // which allows building arbitrarily large numbers.
    let big_number = BigInt::from_str_radix(
        "9876543210987654321098765432109876543210",
        10,
    ).expect("valid big integer");

    // Choose how many digits to extract.
    let n = 15;

    // Extract the first n digits.
    let result = first_n_digits(&big_number, n);

    // Display the result.
    println!("First {} digits: {}", n, result);
}


/*
run:

First 15 digits: 987654321098765

*/

 



answered Aug 14 by avibootz
...