If N=1, the inner sum is empty, so the answer is 0. Assume N≥2 below.
For a fixed d, define
Hd=1≤i<j≤N
Let x=i−1, y=j−i−1, and z. Then are nonnegative integers satisfying , hence
Hd=x+y+z=N−2
For three distinct values a,b,c,
x+y+z=k
Substituting a=d−1, b=d, c=d+1, and gives
Hd=2(d−1)
Let fd=dN. Twice the required value is
d=1∑M−1(M−d)(f
After collecting the coefficient of each fk, every coefficient for 2≤k≤M−1 cancels, and only remains. Since , the original expression equals
2MN−M.
Compute MN by binary exponentiation and multiply by the modular inverse of 2, which is 499122177 modulo 998244353.
The time complexity is O(logN) and the memory complexity is O(1).
Solution written by GPT5.6