def f(n,m,a,b): c=0 while 1: if a>=m:c+=a//m*n*(n-1)//2;a%=m if b>=m:c+=b//m*n;b%=m y=a*n+b if y