2

I want to perform a big mod (%) operation like the example below:

083123456787654325500479087654 % 55

As you can see this number is bigger than Int64.max (9223372036854775807)

I tried to parse this "083123456787654325500479087654" from string into a Decimal but I can't perform mod operation with two Decimals.

Any suggestions?

jscs
  • 63,694
  • 13
  • 151
  • 195
  • There is an answer [HERE](https://stackoverflow.com/a/27281815/9333764) you can use this [git project](https://github.com/githotto/osxgmp) to accomplish a BigInt – Jake Feb 28 '18 at 21:54

1 Answers1

0

You can define a custom mod operator between two decimals such as follow. I haven't the time to test for all scenarios. So I'm selecting the simplest case: modulo between 2 positive numbers. You can expand it to suit your situation:

func % (lhs: Decimal, rhs: Decimal) -> Decimal {
    precondition(lhs > 0 && rhs > 0)

    if lhs < rhs {
        return lhs
    } else if lhs == rhs {
        return 0
    }

    var quotient = lhs / rhs
    var rounded = Decimal()
    NSDecimalRound(&rounded, &quotient, 0, .down)

    return lhs - (rounded * rhs)
}

let a = Decimal(string: "083123456787654325500479087654")!
print(a % 55)

The result is 49.

Mike Henderson
  • 2,028
  • 1
  • 13
  • 32