This page is still under construction.

Parts of this page are still being built. What you see may change.

Vera and Love Triangles

Time limit2sMemory limit256 MB

Summary
For each pair of friends, a crush direction is set by the parity of the bit-count of a modular power expression; count cyclic triples.
Level

Hard9 of 10

Topics
Combinatorics, Number theory, Math, Implementation
Solved
No attempts yet

Problem

Vera has NN friends numbered 00 through N−1N-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 xx, let g(x)g(x) be the number of ones in the binary representation of xx. With integer constants AA, BB, MM, define f(i,j)=g((A⋅Bi⋅N+j) mod M)f(i, j) = g((A \cdot B^{i \cdot N + j}) \bmod M).

For friends ii and jj with i<ji < j, friend ii has a crush on friend jj when f(i,j)f(i, j) is even, and friend jj has a crush on friend ii when f(i,j)f(i, j) is odd.

Vera finds love triangles funny. A love triangle is a set of three friends ii, jj, kk such that ii has a crush on jj, jj has a crush on kk, and kk has a crush on ii.

Given NN, MM, AA, BB, count the love triangles among Vera's friends. Two love triangles are different when their sets of three friends differ.

Input

The first line contains NN, MM, AA, BB separated by spaces.

Constraints:

  • 3≤N≤2000003 \le N \le 200000, 3≤M≤2000003 \le M \le 200000
  • 0<A<M0 < A < M, 0<B<M0 < B < M
  • NN, MM, AA, BB are integers.
  • MM is prime.

Output

Print the number of love triangles on one line.

Hint

Write a→ba \to b when friend aa has a crush on friend bb.

In the first sample, f(0,1)=g(2)=1f(0, 1) = g(2) = 1, f(0,2)=g(3)=2f(0, 2) = g(3) = 2, and f(1,2)=g(2)=1f(1, 2) = g(2) = 1. So 0→20 \to 2, 2→12 \to 1, 1→01 \to 0, and there is one love triangle.

In the second sample, 1→01 \to 0, 2→02 \to 0, and 2→12 \to 1, so there is no love triangle.

Examples3

  1. Example 1

    Input
    3 5 3 4
    
    Expected output
    1
    
  2. Example 2

    Input
    3 3 1 2
    
    Expected output
    0
    
  3. Example 3

    Input
    1337 10007 1337 1337
    
    Expected output
    99141170