Skip to content

Instantly share code, notes, and snippets.

@konjoot
Last active January 4, 2018 09:47
Show Gist options
  • Save konjoot/c6037a77f2857386a1d42ec420c81ed9 to your computer and use it in GitHub Desktop.
Save konjoot/c6037a77f2857386a1d42ec420c81ed9 to your computer and use it in GitHub Desktop.
Safe mod
package main
import "fmt"
func main() {
for a, b := range map[int]int{
-1: 100,
-101: 100,
245: 100,
345: -100,
1: -100,
} {
fmt.Printf("\na = %d, b = %d\n", a, b)
fmt.Println("(a%b + b) % b = ", (a%b+b)%b)
fmt.Println(" a % b = ", a%b)
}
}
// Output:
// a = 345, b = -100
// (a%b + b) % b = -55
// a % b = 45
// a = 1, b = -100
// (a%b + b) % b = -99
// a % b = 1
// a = -1, b = 100
// (a%b + b) % b = 99
// a % b = -1
// a = -101, b = 100
// (a%b + b) % b = 99
// a % b = -1
// a = 245, b = 100
// (a%b + b) % b = 45
// a % b = 45
// https://play.golang.org/p/41VNkZUNk5J
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment