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ββ(dβ1)iβ1djβiβ1(d+1)Nβj.
Let x=iβ1, y=jβiβ1, and z=Nβj. Then x,y,z are nonnegative integers satisfying x+y+z=Nβ2, hence
Hdβ=x+y+z=Nβ2ββ(dβ1)xdy(d+1)z.
For three distinct values a,b,c,
x+y+z=kββaxbycz=(aβb)(aβc)ak+2β+(bβa)(bβc)bk+2β+(cβa)(cβb)ck+2β.
Substituting a=dβ1, b=d, c=d+1, and k=Nβ2 gives
Hdβ=2(dβ1)Nβ2dN+(d+1)Nβ.
Let fdβ=dN. Twice the required value is
d=1βMβ1β(Mβd)(fdβ1ββ2fdβ+fd+1β).
After collecting the coefficient of each fkβ, every coefficient for 2β€kβ€Mβ1 cancels, and only fMββMf1β remains. Since f1β=1, 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