import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.math.BigInteger; import java.util.Arrays; import java.util.Random; import java.util.Scanner; class Main { public static void main(String[] args) throws Exception { new Main().run(); // new Main().generate(); // new Main().judge(args[0]); } void judge(String args0) throws Exception { File file_in = new File(args0); BufferedReader br_in = new BufferedReader(new FileReader(file_in)); Scanner sc = new Scanner(System.in); long p = Integer.parseInt(br_in.readLine()); long k = Integer.parseInt(br_in.readLine()); long a = Integer.parseInt(br_in.readLine()); long x = Integer.parseInt(sc.next()); long g=gcd(k,p-1); if(pow(a,(p-1)/g,p)!=1) { assert(x==-1); }else { assert(pow(x,k,p)==a); } br_in.close(); } void generate() { long p=-1; long k=-1; long a=-1; while(!(2<=p&&p<=1e9+7))p=BigInteger.probablePrime(20, new Random()).longValue(); while(!(2<=k&&k<=1000))k=(int)(Math.random()*2000)%1000; while(!(2<=a&&a0) { a=peth_root(a, pow(div,sz,p), p); } } if(g>1)a=peth_root(a,g,p); return a; } long peth_root(long a,long k,long p) { long sz=p-1; int s=0; while(sz%k==0){sz/=k;++s;} long q1=sz;//q long q2=(p-1)/sz; long ans=pow(a,((k-1)*inv(q1,k)%k*q1+1)/k,p); long c=2; while(pow(c,(p-1)/k,p)==1){++c;} c=pow(c,q1,p); while(true){ long err=pow(ans,k,p)*inv(a,p)%p; int bit=s-cnt(err,k,p); if(bit==s)break; if(bit==0)throw new AssertionError(); ans=ans*pow(c,pow(k,bit-1,p),p)%p; } if(pow(ans,k,p)!=a)throw new AssertionError(); return ans; } int cnt(long a,long base,long p){ int ret=0; while(a!=1){ a=pow(a,base,p); ++ret; } return ret; } long inv(long a,long p){ a%=p; long u=1,v=0; long b=p; while(b>0) { long q=a/b; a%=b; u-=v*q%p; u%=p; { u^=v; v^=u; u^=v; a^=b; b^=a; a^=b; } } //if(a!=1)throw new AssertionError(); return (u%p+p)%p; } long pow(long a,long n,long p){ long r=1; for(;n>0;n>>=1,a=a*a%p)if(n%2==1)r=r*a%p; return r; } long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } static void tr(Object... objects) { System.out.println(Arrays.deepToString(objects)); } }