using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Diagnostics; using System.Diagnostics.Contracts; using CT = System.Diagnostics.Contracts.Contract; class TEST{ static void Main(){ Sol mySol =new Sol(); mySol.Solve(); } } class Sol{ public void Solve(){ // O( W + Q*(H+log(mod)) ) where mod / W = H, W:Initialize of BabyStep, H: Giant Step query; StringBuilder sb = new StringBuilder(); long W = (int) 5e6; long H = mod / W + 1; DiscreteLog.Init(mod, primRoot, W); long Inv2 = ModInv(2,mod); for(int i=0;i D = new Dictionary((int)w+1); long xx = 1; for(long j=0;j= mod - 1){ return true; }else{ return false; } } D.Add(xx,j); xx *= x; xx %= mod; } long nxx = ModInv(xx,mod); long yy = nxx; for(long i=1;i= mod - 1){ return true; }else{ return false; } } yy *= nxx; yy %= mod; } return true; } static long ModInv(long x, long mod){ long a = 0, b = 0, c = 0; if(x == 0) return 0; ExtGCD(x, mod, ref a, ref b, ref c); if(c != 1)return 0; return (a + mod) % mod; } static void ExtGCD(long x,long y,ref long a,ref long b,ref long c){ long r0 = x; long r1 = y; long a0 = 1; long a1 = 0; long b0 = 0; long b1 = 1; long q1, r2, a2, b2; while(r1 > 0){ q1 = r0 / r1; r2 = r0 % r1; a2 = a0 - q1 * a1; b2 = b0 - q1 * b1; r0 = r1; r1 = r2; a0 = a1; a1 = a2; b0 = b1; b1 = b2; } c = r0; a = a0; b = b0; } static long ModPow(long x,long k,long mod){ if(k == 0)return 1; if(x == 0)return 0; long ret = 1; long xx = x; while(k>0){ if((k&1)==1){ret *= xx; ret %= mod;} xx *= xx; xx %= mod; k>>=1; } return ret; } static String rs(){return Console.ReadLine();} static int ri(){return int.Parse(Console.ReadLine());} static long rl(){return long.Parse(Console.ReadLine());} static double rd(){return double.Parse(Console.ReadLine());} static String[] rsa(char sep=' '){return Console.ReadLine().Split(sep);} static int[] ria(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>int.Parse(e));} static long[] rla(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>long.Parse(e));} static double[] rda(char sep=' '){return Array.ConvertAll(Console.ReadLine().Split(sep),e=>double.Parse(e));} } class DiscreteLog{ static long mod; static long primRoot; static long WInvPrimRoot; // Pow(primRoot , -W) static long W,H; static Dictionary WTable; public static void Init(long mod_, long primRoot_, long w){ mod = mod_; primRoot = primRoot_; W = w; H = mod / w + 1; WTable = new Dictionary((int)W+20); long xx = 1; for(long j=0;j0){ if((k&1)==1){ret *= xx; ret %= mod;} xx *= xx; xx %= mod; k>>=1; } return ret; } }