Vera has N friends numbered 0 through N−1. They all study software engineering, so none of them has spare time for a relationship, but they still have crushes on each other.
For a non-negative integer x, let g(x) be the number of ones in the binary representation of x. With integer constants A, B, M, define f(i,j)=g((A⋅Bi⋅N+j)modM).
For friends i and j with i<j, friend i has a crush on friend j when f(i,j) is even, and friend j has a crush on friend i when f(i,j) is odd.
Vera finds love triangles funny. A love triangle is a set of three friends i, j, k such that i has a crush on j, j has a crush on k, and k has a crush on i.
Given N, M, A, B, count the love triangles among Vera's friends. Two love triangles are different when their sets of three friends differ.