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

1 Answer

0 votes
import Foundation

/// Encapsulates a high-precision large integer backed by string storage.
public struct BigInteger: CustomStringConvertible {
    /// Internal string representation of numerical digits.
    private let digits: String
    
    /// Creates a new `BigInteger` from a string representation.
    /// - Parameter value: A valid numeric string (e.g., "9876543210...").
    public init(_ value: String) {
        // Strip leading whitespace and account for signs
        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
        if trimmed.hasPrefix("-") || trimmed.hasPrefix("+") {
            self.digits = String(trimmed.dropFirst())
        } else {
            self.digits = trimmed
        }
    }
    
    /// String representation conforming to `CustomStringConvertible`.
    public var description: String {
        return digits
    }
    
    /// Extracts up to the first N digits of the `BigInteger`.
    ///
    /// This method uses Swift's standard collection slicing (`prefix(_:)`),
    /// which operates in $O(N)$ time complexity based on requested count rather than total length,
    /// returning an efficient zero-copy Substring slice.
    ///
    /// - Parameter count: The number of leading digits requested.
    /// - Returns: A `Substring` containing up to `count` leading digits.
    public func firstNDigits(_ count: Int) -> Substring {
        guard count > 0 else { return "" }
        return digits.prefix(count)
    }
}

/// Standalone utility function for extracting leading digits directly from raw numeric strings.
///
/// - Parameters:
///   - numberString: The raw string representation of a large integer.
///   - count: The number of leading digits desired.
/// - Returns: A Substring representing the first N digits.
func extractFirstDigits(from numberString: String, count: Int) -> Substring {
    guard count > 0 else { return "" }
    
    // Ignore leading negative or positive signs
    let isSigned = numberString.hasPrefix("-") || numberString.hasPrefix("+")
    let digitSlice = isSigned ? numberString.dropFirst() : numberString[...]
    
    // `prefix` safely handles cases where requested count exceeds total digits
    return digitSlice.prefix(count)
}

// ==========================================
// Program Execution
// ==========================================

let largeNumberString = "9876543210123456789098765432109876543210"
let digitCount = 7

// 1. Using the BigInteger wrapper type
let bigInt = BigInteger(largeNumberString)
let leadingSliceFromStruct = bigInt.firstNDigits(digitCount)

// 2. Using the standalone functional utility
let leadingSliceFromFunc = extractFirstDigits(from: largeNumberString, count: digitCount)

print("Original Large Integer: \(largeNumberString)")
print("First \(digitCount) Digits (via BigInteger): \(leadingSliceFromStruct)")
print("First \(digitCount) Digits (via Utility Function): \(leadingSliceFromFunc)")



/*
run:

Original Large Integer: 9876543210123456789098765432109876543210
First 7 Digits (via BigInteger): 9876543
First 7 Digits (via Utility Function): 9876543

*/

 



answered Aug 14 by avibootz
...