Skip to content

Instantly share code, notes, and snippets.

@vpereira01
Last active May 15, 2022 09:41
Show Gist options
  • Save vpereira01/85572bf4c7c80765d76decde94384fb1 to your computer and use it in GitHub Desktop.
Save vpereira01/85572bf4c7c80765d76decde94384fb1 to your computer and use it in GitHub Desktop.
go big int faster increment
// bigIntInc speeds up z.Add(z, one) operations when z > 0
func bigIntInc(z *big.Int) {
zBits := z.Bits()
// big.NewInt( 9).Sign() == 1
// For speed and simplicity this only tries to increment the least significant digits.
// Using a base 10 example: 1000+1 only affects the least significant digit.
// Only when the least significant digit is 9, 1009+1, then more significant digits are affected.
if z.Sign() > 0 && zBits[0] < math.MaxUint {
// overflow does not happen due to zBits[0] < math.MaxUint check
// uint(zBits[0])++ is not allowed by Go
zBits[0] = big.Word(uint(zBits[0]) + 1)
} else {
z.Add(z, one)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment