package main import . "fmt" func main() { check() var x, n int64 Scan(&x, &n) Println(solve(x, n)) } func check() { for x := int64(-1000); x <= 1000; x++ { for n := int64(1); n <= 1000; n++ { br := bruteforce(x, n) sr := solve(x, n) if br != sr { panic(Errorf("x=%d,n=%d,br=%d,sr=%d",x,n,br,sr)) } } } } func bruteforce(x, n int64) int64 { for i := int64(1); i <= n; i++ { if x <= 0 { x += i } else { x -= i } } return x } func init() { if res := bruteforce(2, 3); res != 2 { panic(Errorf("x=2,n=3,ans=2,res=%d",res)) } if res := bruteforce(10, 3); res != 4 { panic(Errorf("x=10,n=3,ans=4,res=%d",res)) } } func solve(x, n int64) int64 { ax := x if ax < 0 { ax = -ax } upper := int64(2e9) lower := int64(0) for lower + 1 < upper { v := (upper+lower)/2 sum := v*(v+1)/2 if sum < ax { lower = v } else { upper = v } } if upper > n { upper = n } if x <= 0 { x += upper*(upper+1)/2 } else { x -= upper*(upper+1)/2 } if upper == n { return x } if x <= 0 { if (n-upper)%2 == 0 { x -= (n-upper)/2 } else { x += upper+1 + (n-upper)/2 } } else { if (n-upper)%2 == 0 { x += (n-upper)/2 } else { x -= upper+1 + (n-upper)/2 } } return x }