Under construction

Still being built. Things may change

The One Polynomial Man

Time limit4sMemory limit512 MB

Summary
Count ordered pairs (a, b) from S where the rational expression in a and b, taken mod p, lands in V. Pairs with a zero denominator fail.
Level

Medium7 of 10

Topics
Math, Number theory, Hash map
Solved
No attempts yet

Problem

Is it a programming contest? You are given a prime pp and two subsets SS and VV of residues from 00 to p−1p-1. Count the pairs (a,b)(a, b) that satisfy all three conditions: first, (∏z∈V((2a+3b)2+5a2(3a+b)2+(2a+5b)2+3b2(3a+2b)2−z))≡0\left(\prod_{z \in V}\left(\frac{(2a+3b)^2 + 5a^2}{(3a+b)^2} + \frac{(2a+5b)^2 + 3b^2}{(3a+2b)^2} - z\right)\right) \equiv 0; second, a∈Sa \in S; third, b∈Sb \in S. All operations are performed modulo pp. When a≠ba \ne b, the pairs (a,b)(a, b) and (b,a)(b, a) count as different. Division by zero is not allowed: if either denominator is zero, the congruence is considered false.

Input

The first line contains a prime pp (2≤p≤1062 \le p \le 10^6). The second line contains nn, the size of SS (0≤n≤p0 \le n \le p). The third line contains the nn distinct elements S1,S2,…,SnS_1, S_2, \dots, S_n (0≤Si≤p−10 \le S_i \le p-1). The fourth line contains mm, the size of VV (0≤m≤p0 \le m \le p). The fifth line contains the mm distinct elements V1,V2,…,VmV_1, V_2, \dots, V_m (0≤Vi≤p−10 \le V_i \le p-1).

Output

Print one integer: the number of solutions.

Examples2

  1. Example 1

    Input
    7
    4
    0 4 5 6
    2
    2 3
    
    Expected output
    8
    
  2. Example 2

    Input
    19
    10
    0 3 4 5 8 9 13 14 15 18
    10
    2 3 5 9 10 11 12 13 14 15
    
    Expected output
    42