Skip to content

Instantly share code, notes, and snippets.

@sssbohdan
Created May 6, 2023 19:23
Show Gist options
  • Save sssbohdan/e18447f009e749746e0729dcd60120d0 to your computer and use it in GitHub Desktop.
Save sssbohdan/e18447f009e749746e0729dcd60120d0 to your computer and use it in GitHub Desktop.
BigInt1.swift
struct BigInt {
private let overflows: UInt64
private var remainder: UInt64
func add(_ x: BigInt) -> BigInt {
let totalOverflows = self.overflows + x.overflows
let result = self.remainder.addingReportingOverflow(x.remainder)
return BigInt(
overflows: totalOverflows + (result.overflow ? 1 : 0),
remainder: result.partialValue)
}
//((a * n) + c1) * ((b * n) + c2) = (a * n) * (b * n) + (a * n) * c2 + c1 * (b * n) + c1 * c2
func multiply(by x: BigInt) -> BigInt {
let totalOverflows = self.overflows.multipliedReportingOverflow(by: x.overflows)
let xRemainderOverflows = self.overflows.multipliedReportingOverflow(by: x.remainder)
let selfRemainderOverflow = self.remainder.multipliedReportingOverflow(by: x.overflows)
let remainder = self.remainder.multipliedReportingOverflow(by: x.remainder)
return BigInt(
overflows: totalOverflows.partialValue
+ xRemainderOverflows.partialValue
+ selfRemainderOverflow.partialValue
+ (remainder.overflow ? 1 : 0),
remainder: remainder.partialValue
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment