As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where p is an odd prime number, the functional equation states that  for some function . (This equation should hold for any integer x in the range 0 to p - 1, inclusive.)It turns out that f can actually be many different functions. Instead of finding a solution, Kevin wants you to count the number of distinct functions f that satisfy this equation. Since the answer may be very large, you should print your result modulo 109 + 7.

The input consists of two space-separated integers p and k (3 ≤ p ≤ 1 000 000, 0 ≤ k ≤ p - 1) on a single line. It is guaranteed that p is an odd prime number.

Print a single integer, the number of distinct functions f modulo 109 + 7.

NoteIn the first sample, p = 3 and k = 2. The following functions work:   f(0) = 0, f(1) = 1, f(2) = 2.  f(0) = 0, f(1) = 2, f(2) = 1.  f(0) = f(1) = f(2) = 0.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int k = in.nextInt();
		long r = 1, mod = (long) (1e+9 + 7);
		if (k == 0) {
			for (int i = 1; i < n; i++) {
				r = (r * n) % mod;
			}
			System.out.println(r);
			return;
		}
		if (k == 1) {
			for (int i = 0; i < n; i++) {
				r = (r * n) % mod;
			}
			System.out.println(r);
			return;
		}
		int[] multiplier = new int[n];
		for (int i = 1; i < n; i++) {
			int pos = i;
			if (multiplier[pos] != 0) {
				continue;
			}
			r = (r * n) % mod;
			while (multiplier[pos] != 1) {
				multiplier[pos] = 1;
				pos = (int) (((long) pos * (long) k) % (long) n);
			}
		}
		System.out.println(r);
	}

}

import java.io.*;
import java.lang.Math;
import java.util.*;

public class Main
{
	public BufferedReader in;
	public PrintStream out;

	public boolean log_enabled = true;

	public long M = 1000000007;

	public void test()
	{
		long p = readInt();
		long k = readInt();

		long x = k;
		long c = 1;

		if (k==0)
		{
			k = p-1;
		}
		else if (k==1)
		{
			k = p;
		}
		else
		{
			while (x!=1)
			{
				c ++;
				x = (k*x) % p;
			}

			k = (p-1) / c;
		}

		x = 1;
		long d = 1;
		while (2*d <= k) d *= 2;

		while (d>0)
		{
			x = (x * x) % M;
			if ((k & d) > 0)
			{
				x = (x * p) % M;
			}

			d = d >> 1;
		}

		out.println(x);
	}

	public void run()
	{
		try
		{
			in = new BufferedReader(new InputStreamReader(System.in));
			out = System.out;

			//in = new BufferedReader(new FileReader("in.txt"));
			//out = new PrintStream(new File("out.txt"));

		}
		catch (Exception e)
		{
			return;
		}

		//while (true)
		{
			//int t = readInt(); for (int i=0; i<t; i++)
			{
				test();
			}
		}
	}

	public static void main(String args[])
	{
		new Main().run();
	}

	private StringTokenizer tokenizer = null;

	public int readInt()
	{
        return Integer.parseInt(readToken());
    }

    public long readLong()
	{
        return Long.parseLong(readToken());
    }

    public double readDouble()
	{
        return Double.parseDouble(readToken());
    }

	public String readLn()
	{
		try
		{
			String s;
			while ((s = in.readLine()).length()==0);
			return s;
		}
		catch (Exception e)
		{
			return "";
		}
	}

    public String readToken()
	{
		try
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				tokenizer = new StringTokenizer(in.readLine());
			}
			return tokenizer.nextToken();
		}
		catch (Exception e)
		{
			return "";
		}
    }

	public int[] readIntArray(int n)
	{
		int[] x = new int[n];
		readIntArray(x, n);
		return x;
	}

	public void readIntArray(int[] x, int n)
	{
		for (int i=0; i<n; i++)
		{
			x[i] = readInt();
		}
	}

	public void logWrite(String format, Object... args)
	{
		if (!log_enabled)
		{
			return;
		}

		out.printf(format, args);
	}
}

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
	  br = new BufferedReader(new FileReader("input.txt"));
	  pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
	  br = new BufferedReader(new InputStreamReader(System.in));
	  pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	public static void main(String[] args) throws Exception {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		//int qq = 1;
		int qq = Integer.MAX_VALUE;
		//int qq = readInt();
		for(int casenum = 1; casenum <= qq; casenum++)	{
			int n = readInt();
			int k = readInt();
			final int MOD = 1000000007;
			if(k == 0) {
				long ret = 1;
				for(int a = 1; a < n; a++) {
					ret *= n;
					ret %= MOD;
				}
				pw.println(ret);
				continue;
			}
			long[] fact = new long[n+1];
			boolean[] seen = new boolean[n];
			int[] numCycles = new int[n+1];
			long ret = 1;
			fact[0] = 1;
			for(int i = 1; i <= n; i++) {
				fact[i] = fact[i-1] * i;
				fact[i] %= MOD;
			}
			for(int i = 0; i < n; i++) {
				if(seen[i]) continue;
				int len = 0;
				long curr = i;
				while(!seen[(int)curr]) {
					seen[(int)curr] = true;
					len++;
					curr *= k;
					curr %= n;
				}
				numCycles[len]++;
			}
			for(int i = 0; i <= n; i++) {
				if(numCycles[i] == 0) continue;
				long amtForOne = 0;
				for(int a = 1; a * a <= i; a++) {
					if(i%a == 0) {
						amtForOne += numCycles[a] * 1L * a;
						amtForOne %= MOD;
						if(a * a != i) {
							amtForOne += numCycles[(i/a)] * 1L * (i/a);
							amtForOne %= MOD;
						}
					}
				}
				for(int a = 0; a < numCycles[i]; a++) {
					ret *= amtForOne;
					ret %= MOD;
				}
			}
			pw.println(ret);
		}
		exitImmediately();
	}

	private static void exitImmediately() {
		pw.close();
		System.exit(0);
	}

	private static long readLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	private static double readDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	private static String nextLine() throws IOException  {
		if(!br.ready()) {
			exitImmediately();
		}
		st = null;
		return br.readLine();
	}

	private static String nextToken() throws IOException  {
		while(st == null || !st.hasMoreTokens())  {
			if(!br.ready()) {
				exitImmediately();
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}

import java.util.*;

public class MoodularArithmetic {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		if (k == 0) {
			long ans = 1;
			for (int i = 0; i < p - 1; i++) {
				ans *= p;
				ans %= 1000000007;
			}
			System.out.println(ans);
		}
		else if (k == 1) {
			long ans = 1;
			for (int i = 0; i < p; i++) {
				ans *= p;
				ans %= 1000000007;
			}
			System.out.println(ans);
		}
		else {
			long a = k;
			int ord = 1;
			while (a != 1) {
				a *= k;
				a %= p;
				ord++;
			}
			long ans = 1;
			for (int i = 0; i < (p - 1) / ord; i++) {
				ans *= p;
				ans %= 1000000007;
			}
			System.out.println(ans);
		}
		sc.close();
		System.exit(0);
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main
{

    public static final long MOD = 1000000007;

   void solve() throws Exception
    {
        int p = nextInt();
        long k = nextInt();
        boolean[] q = new boolean[ p ];
        int s = 0;
        for( int i = 1; i < p; i++ ) if( !q[ i ] )
        {
            s++;
            for( int j = i; !q[ j ]; j = ( int ) ( k * j % p ) ) q[ j ] = true;
        }
        if( k == 1 ) s++;
        long ans = 1;
        for( int i = 0; i < s; i++ ) ans = ans * p % MOD;
        out.println( ans );
    }

    public static void main( String[] args )
    {
        new Main().run();
    }

    public void run()
    {
        try
        {
            in = new BufferedReader( new InputStreamReader( System.in ) );
            out = new PrintWriter( System.out );
            solve();
        }
        catch( Exception e )
        {
            e.printStackTrace();
            System.exit( 1 );
        }
        finally
        {
            out.close();
        }
    }

    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

    String nextToken() throws IOException
    {
        while( st == null || !st.hasMoreTokens() ) st = new StringTokenizer( in.readLine() );
        return st.nextToken();
    }

    int nextInt() throws IOException
    {
        return Integer.parseInt( nextToken() );
    }

    long nextLong() throws IOException
    {
        return Long.parseLong( nextToken() );
    }

}

import java.util.*;

public class Modular {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        long p = scan.nextInt();
        long k = scan.nextInt();
        long mod = (long)Math.pow(10, 9) + 7;

        if(k > 1 && (k < p - 1)) {
            int numOfLoops = 0;
            boolean[] loops = new boolean[(int)p];
            for(int i = 1; i < loops.length; i++) {
                if(loops[i] == false) {
                    numOfLoops++;
                    loops[i] = true;
                    long j = (i * k) % p;
                    while(j != i) {
                        loops[(int)j] = true;
                        j = (j * k) % p;
                    }
                }
            }
            long res = 1;
            for(int i = 1; i <= numOfLoops; i++) {
                res = (res * p) % mod;
            }
            System.out.println(res);
            return;
        }

        long half = (p - 1) / 2;
        long res = 1;

        for(long i = 1; i <= half; i++) {
            res = (res * p) % mod;
        }

        if(k == p - 1) {
            System.out.println(res);
            return;
        }

        for(long i = half+1; i <= p-1; i++) {
            res = (res * p) % mod;
        }

        if(k == 0) {
            System.out.println(res);
            return;
        }

        res = (res * p) % mod;
        System.out.println(res);
    }
}

import java.util.*;
import java.io.*;

public class B
{
   public static void main(String[] args) throws Exception
   {
      PrintWriter out = new PrintWriter(System.out);
      new B(new FastScanner(System.in), out);
      out.close();
   }

   int MODO = 1_000_000_007;

   int mpow(int p, int e)
   {
      long res = 1L;
      while (e-->0)
      {
         res *= p;
         res %= MODO;
      }
      return (int)res;
   }

   public B(FastScanner in, PrintWriter out)
   {
      int p = in.nextInt();
      int k = in.nextInt();

      if (k == 0)
      {
         out.println(mpow(p, p-1));
         return;
      }

      if (k == 1)
      {
         out.println(mpow(p, p));
         return;
      }

      int[] g = new int[p];
      for (int i=0; i<p; i++)
         g[i] = (int)((k*1L*i) % p);

      boolean[] seen = new boolean[p];

      int e = 0;
      for (int i=1; i<p; i++)
      {
         if (!seen[i])
         {
            e++;
            int j = i;
            while (!seen[j])
            {
               seen[j] = true;
               j = g[j];
            }
         }
      }

      out.println(mpow(p, e));
   }
}

class FastScanner{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public FastScanner(InputStream stream)
    {
        this.stream = stream;
    }

    int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    boolean isSpaceChar(int c)
    {
        return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
    }

    boolean isEndline(int c)
    {
        return c=='\n'||c=='\r'||c==-1;
    }

    int nextInt()
    {
        return Integer.parseInt(next());
    }

    long nextLong()
    {
        return Long.parseLong(next());
    }

    double nextDouble()
    {
        return Double.parseDouble(next());
    }

    String next(){
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do{
            res.appendCodePoint(c);
            c = read();
        }while(!isSpaceChar(c));
        return res.toString();
    }

    String nextLine(){
        int c = read();
        while (isEndline(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do{
            res.appendCodePoint(c);
            c = read();
        }while(!isEndline(c));
        return res.toString();
    }
}

import java.lang.*;
import java.io.*;
import java.util.*;
import java.math.*;

import static java.lang.Math.*;

public class Solution implements Runnable {

	final int MOD = (int)(1e9) + 7;

	int binPow(int a, int n) {
		int res = 1;
		while (n > 0) {
			if ((n & 1) == 1) {
				res = (int)(res * 1L * a % MOD);
			}
			n >>= 1;
			a = (int)(a * 1L * a % MOD);
		}
		return res;
	}

	int[] cl, size;

	int getRoot(int v) {
		return (cl[v] == v ? v : (cl[v] = getRoot(cl[v])));
	}

	void union(int v, int u) {
		if (v == u)
			return;
		if (size[v] >= size[u]) {
			cl[u] = v;
			size[v] += size[u];
		} else {
			cl[v] = u;
			size[u] += size[v];
		}
	}

	void solve() throws Exception {
		int p = sc.nextInt();
		int k = sc.nextInt();
		if (k == 0) {
			out.println(binPow(p, p - 1));
			return;
		}
		if (k == 1) {
			out.println(binPow(p, p));
			return;
		}
		cl = new int[p];
		size = new int[p];
		for (int i = 0; i < p; i++) {
			cl[i] = i;
			size[i] = 1;
		}
		for (int i = 1; i < p; i++) {
			int v = getRoot(i);
			int u = getRoot((int)(i * 1L * k % p));
			union(v, u);
		}
		int ans = 1;
		boolean[] was = new boolean[p];
		for (int i = 1; i < p; i++) {
			int v = getRoot(i);
			if (!was[v])
				ans = (int)(ans * 1L * p % MOD);
			was[v] = true;
		}
		out.println(ans);
	}

	BufferedReader in;
	PrintWriter out;
	FastScanner sc;

	final String INPUT_FILE = "";
	final String OUTPUT_FILE = "";

	static Throwable throwable;

	public static void main(String[] args) throws Throwable {
		Thread thread = new Thread(null, new Solution(), "", (1 << 26));
		thread.start();
		thread.join();
		thread.run();
		if (Solution.throwable != null)
			throw Solution.throwable;
	}

	public void run() {
		try {
			if (INPUT_FILE.equals("")) {
				in = new BufferedReader(new InputStreamReader(System.in));
			} else {
				in = new BufferedReader(new FileReader(INPUT_FILE));
			}
			if (OUTPUT_FILE.equals("")) {
				out = new PrintWriter(System.out);
			} else {
				out = new PrintWriter(OUTPUT_FILE);
			}
			sc = new FastScanner(in);
			solve();
		} catch (Exception e) {
			throwable = e;
		} finally {
			out.close();
		}
	}

}

class FastScanner {

	BufferedReader reader;
	StringTokenizer strTok;

	FastScanner(BufferedReader reader) {
		this.reader = reader;
	}

	public String nextToken() throws Exception {
		while (strTok == null || !strTok.hasMoreTokens()) {
			strTok = new StringTokenizer(reader.readLine());
		}
		return strTok.nextToken();
	}

	public int nextInt() throws Exception {
		return Integer.parseInt(nextToken());
	}

	public double nextDouble() throws Exception {
		return Double.parseDouble(nextToken());
	}

	public long nextLong() throws Exception {
		return Long.parseLong(nextToken());
	}
}

import java.io.*;
import java.util.*;

/**
 * @auther chao
 * @date 15/12/30
 */
public class A {
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);
        long k, p;
        p = in.nextLong();
        k = in.nextLong();
        long x = 1;
        long m = p-1;
        final long MOD = 1000000007l;
        for (int i = 1; i < p; i++) {
            x = (x*k)%p;
            if (x == 1) {
                m = i;
                break;
            }
        }
        long ans;
        if (k == 0) {
            ans = getPow(p, p-1, MOD);
        } else if (k == 1) {
            ans = getPow(p, p, MOD);
        } else {
            ans = getPow(p, (p-1)/m, MOD);
        }
        System.out.println(ans);
    }

    private static long getPow(long x, long p, long mod) {
        x = x%mod;
        if (p == 0) return 1;
        long res = (p&1) == 0 ? 1 : x;
        long y = getPow(x, p/2, mod);
        y = (y*y)%mod;
        return (res*y)%mod;
    }
}

import java.util.Scanner;

public class B {
	static final long MOD = 1000000007L;

	static long pow(long b, long e) {
		long ans = 1;
		for (int i = 0; i < e; i++) {
			ans*=b;
			ans%=MOD;
		}
		return ans;
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long p = sc.nextLong();
		long k = sc.nextLong();
		long ans = 0;
		if (k == 0) {
			ans = pow(p, p - 1);
		} else if (k == 1){
			ans = pow(p, p);
		} else {
			int e = 1;
			long pow = k;
			while (pow != 1) {
				e++;
				pow*=k;
				pow%=p;
			}
			ans = pow(p, (p-1)/e);
		}
		System.out.println(ans);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        static final long MODULO = (long) 1e9 + 7;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int p = in.nextInt();
            int k = in.nextInt();
            int pw;
            if (k == 0) {
                pw = p - 1;
            } else {
                pw = 1;
                int prod = k;
                while (prod != 1) {
                    prod = (int) (prod * (long) k % p);
                    ++pw;
                }
                pw = (p - 1) / pw;
                if (k == 1)
                    ++pw;
            }
            long res = 1;
            for (int i = 0; i < pw; ++i)
                res = res * p % MODULO;
            out.println(res);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

import java.io.*;
import java.util.*;
public class B603 {
public static void main(String[] args) throws IOException {
    input.init(System.in);
    PrintWriter out = new PrintWriter(System.out);
    int p = input.nextInt(), k = input.nextInt();
    boolean[] used = new boolean[p];
    used[0] = true;
    int cyc = 1;
    for(int i = 1; i<p; i++)
    {
        if(used[i]) continue;
        int at = i;
        while(true)
        {
            if(used[at]) break;
            used[at] = true;
            at = (int) ((long)at*k%p);
            at %= p;
        }
        cyc++;
    }
    if(k == 0)
    {
        out.println(pow(p,p-1));
    }
    else if(k == 1 || p == 1)
    {
        out.println(pow(p, cyc));
    }
    else
    {
        out.println(pow(p, cyc-1));
    }
    out.close();
}
static long pow(long n, long p)
{
    if(p == 0) return 1;
    if(p%2 == 0)
    {
        long sqrt = pow(n,p>>1);
        return (sqrt*sqrt)%1000000007;
    }
    return (n * pow(n,p-1))%1000000007;
}
public static class input {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    static void init(InputStream input) {
    reader = new BufferedReader(new InputStreamReader(input));
    tokenizer = new StringTokenizer("");
    }

    static String next() throws IOException {
    while (!tokenizer.hasMoreTokens())
        tokenizer = new StringTokenizer(reader.readLine());
    return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
    return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {
    return Double.parseDouble(next());
    }

    static long nextLong() throws IOException {
    return Long.parseLong(next());
    }
}
}

import java.io.*;
import java.util.*;

public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int p = nextInt();
        int k = nextInt();
        long ans = 1;
        boolean used[] = new boolean[p];
        for(int i = 1;i < p;i++) {
            int v = i;
            if (!used[i]) {
                while (!used[v]) {
                    used[v] = true;
                    v = (int)(((long)v * k) % p);
                }
                ans = (ans * p) % inf;
            }
        }

        if (k == 1) ans = (ans * p) % inf;
        pw.println(ans);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by chavit on 01.12.2015.
 */
public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        long res = 1, mod = (long) (1e+9 + 7);
        if (k == 0) {
            for (int i = 1; i < n; i++) {
                res = (res * n) % mod;
            }
            System.out.println(res);
            return;
        }
        if (k == 1) {
            for (int i = 0; i < n; i++) {
                res = (res * n) % mod;
            }
            System.out.println(res);
            return;
        }
        int[] multiplier = new int[n];
        for (int i = 1; i < n; i++) {
            int pos = i;
            if (multiplier[pos] != 0) {
                continue;
            }
            res = (res * n) % mod;
            while (multiplier[pos] != 1) {
                multiplier[pos] = 1;
                pos = (int) (((long) pos * (long) k) % (long) n);
            }
        }
        System.out.println(res);
    }
}

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;

public class B {

    private static final long M = 1000000007;

    static void solve() throws IOException {
        int p = in.nextInt();
        int k = in.nextInt();
        int pow;
        if ( k == 0 ) {
            pow = p - 1;
        } else if ( k == 1 ) {
            pow = p;
        } else {
            int d = 1;
            long t = k;
            while ( t != 1 ) {
                t *= k;
                t %= p;
                d++;
            }
            pow = ( p - 1 ) / d;
        }
        out.println( BigInteger.valueOf( p ).modPow( BigInteger.valueOf( pow ), BigInteger.valueOf( M ) ) );
    }

    static Scanner in;
//    static StreamTokenizer in;
    static PrintWriter out;

//    static int nextInt() throws IOException {
//        in.nextToken();
//        return ( int ) in.nval;
//    }

    public static void main( String[] args ) throws IOException {
        in = new Scanner( System.in );
//        in = new StreamTokenizer( new InputStreamReader( System.in ) );
        out = new PrintWriter( System.out );
        solve();
        out.close();
    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main
{
	static long mod=1000000007;
	static long quick(long a, long b)
	{
		long ans=1;
		while(b!=0)
		{
			if(b%2==1)
				ans=ans*a%mod;
			a=a*a%mod;
			b/=2;
		}
		return ans;
	}
	public static void main(String[] args)
	{
		InputReader in = new InputReader();
		PrintWriter out = new PrintWriter(System.out);
		while(in.hasNext())
		{
			int p=in.nextInt();
			int k=in.nextInt();
			if(k==0)
				out.println(quick(p, p-1));
			else if(k==1)
				out.println(quick(p, p));
			else
			{
				int i=1;
				long cur=k;
				while(cur!=1)
				{
					cur=cur*k%p;
					i++;
				}
				out.println(quick(p, (p-1)/i));
			}
		}
		out.close();
	}
}

class InputReader
{
	BufferedReader buf;
	StringTokenizer tok;
	InputReader()
	{
		buf = new BufferedReader(new InputStreamReader(System.in));
	}

	boolean hasNext()
	{
		while (tok == null || !tok.hasMoreElements())
		{
			try
			{
				tok = new StringTokenizer(buf.readLine());
			}
			catch (Exception e)
			{
				return false;
			}
		}
		return true;
	}

	String next()
	{
		if (hasNext())
			return tok.nextToken();
		return null;
	}

	int nextInt()
	{
		return Integer.parseInt(next());
	}

	long nextLong()
	{
		return Long.parseLong(next());
	}

	double nextDouble()
	{
		return Double.parseDouble(next());
	}

	BigInteger nextBigInteger()
	{
		return new BigInteger(next());
	}

	BigDecimal nextBigDecimal()
	{
		return new BigDecimal(next());
	}
}

import java.io.*;
import java.util.*;

public class modulararithmatic {
    public static void main(String[] args) throws Exception
    {
        InputReader in=new InputReader(System.in);
        PrintWriter pw=new PrintWriter(System.out);
        int n=in.nextInt();
        int k=in.nextInt();
        if(k==0)
        {
            pw.println(pow(n,n-1));
        }
        else if(k==1)
        {
            pw.println(pow(n,n));
        }
        else
        {
            disjointset ds=new disjointset();
            ds.createSet(n);
            for(int i=0;i<n;i++)
            {
                int w=(int)((k *1l* i) % n);

                if(ds.findset(i)!=ds.findset(w))
                {
                ds.mergeset(i, w);
                }
            }
            pw.println(pow(n,ds.connectedcomponent-1));
        }

        pw.close();
    }
    static int MOD=(int)(1e9+7);
    public static long pow(long a,long b){
        if(b == 0)  return 1;
        if(b == 1)  return a % MOD;
        long t = pow(a,b >> 1);
        t = (t * t) % MOD;
        if((b & 1) == 1)
            t = (t * a) % MOD;
        return t;

    }

     static class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[8192];
        private int curChar;
        private int snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int snext() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }

            int res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }

            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));

            return res * sgn;
        }

        public String readString() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }

}

 class disjointset {
    static int[] parent;
    static int[] rank;
    static int connectedcomponent;

    public static void createSet(int n)
    {
        parent=new int[n];
        rank=new int[n];
        for(int i=0;i<n;i++)
        {
            parent[i]=i;
        }
        connectedcomponent=n;
        return;
    }
    public static int findset(int x)
    {
        if(x!=parent[x])
        {
            parent[x]=findset(parent[x]);
        }
        return parent[x];
    }
    public static void mergeset(int x,int y)
    {
        connectedcomponent--;
        int px=findset(x);
        int py=findset(y);
        if(rank[px]>rank[py])
        {
            parent[py]=px;
        }
        else
        {
            parent[px]=py;
        }
        if(rank[px]==rank[py])
        {
            rank[py]++;
        }
    }

}

import java.io.*;
import java.util.*;

public class B {
	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/T";

	FastScanner in;
	PrintWriter out;

	final int MOD = 1000000007;

	public void solve() {
		int p = in.nextInt(), k = in.nextInt();
		if (k == 0) {
			long res = 1;
			for (int i = 1; i < p; i++) {
				res = (res * p) % MOD;
			}
			System.out.println(res);
			return;
		}
		int now = 0;
		int selfLoop = 0;
		for (int i = 0; i < p; i++) {
			if (now == i) selfLoop++;
			now = (now + k) % p;
		}

		int[] next = new int[p];
		long res = 1;
		boolean[] vis = new boolean[p];
		for (long i = 0; i < p; i++) {
			int from = (int)((i * k) % p);
			next[from] = (int)i;
		}

		for (int from = 0; from < p; from++) {
			if (vis[from]) continue;
			int x = from;
			for (int size = 1; size < p; size++) {
				vis[x] = true;
				x = next[x];
				if (x == from) {
					res = (res * (size == 1 ? selfLoop : p)) % MOD;
					break;
				}
			}
		}
		System.out.println(res);
	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		solve();
	}

	public static void main(String[] args) {
		new B().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import java.io.*;
import java.util.*;

public class B {
	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/T";

	FastScanner in;
	PrintWriter out;

	final int MOD = 1000000007;
	int loopSize;
	boolean[] vis;
	int[] next;

	void dfs(int start, int u, int dep) {
		if (start == u && dep != 0) {
			loopSize = dep;
			return;
		}
		vis[u] = true;
		dfs(start, next[u], dep + 1);
	}

	public void solve() {
		int p = in.nextInt(), k = in.nextInt();
		if (k == 0) {
			long res = 1;
			for (int i = 1; i < p; i++)
				res = (res * p) % MOD;
			System.out.println(res);
			return;
		}
		int now = 0;
		int selfLoop = 0;
		for (int i = 0; i < p; i++) {
			if (now == i) selfLoop++;
			now = (now + k) % p;
		}

		long res = 1;
		vis = new boolean[p];
		next = new int[p];
		for (long i = 0; i < p; i++) {
			int from = (int)((i * k) % p);
			next[from] = (int)i;
		}

		for (int from = 0; from < p; from++) {
			if (vis[from]) continue;

			loopSize = -1;
			dfs(from, from, 0);

			if (loopSize == 1) {
				res = (res * selfLoop) % MOD;
			} else {
				res = (res * p) % MOD;
			}
		}
		System.out.println(res);
	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		solve();
	}

	public static void main(String[] args) {
		new B().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import java.io.*;
import java.util.*;

public class B {
	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/T";

	FastScanner in;
	PrintWriter out;

	final int MOD = 1000000007;
	int loopSize;
	boolean[] vis;
	ArrayList<Integer>[] g;

	void dfs(int start, int u, int dep) {
		if (start == u && dep != 0) {
			loopSize = dep;
			return;
		}
		vis[u] = true;
		dfs(start, g[u].get(0), dep + 1);
	}

	public void solve() {
		int p = in.nextInt(), k = in.nextInt();
		if (k == 0) {
			long res = 1;
			for (int i = 1; i < p; i++) {
				res = (res * p) % MOD;
			}
			System.out.println(res);
			return;
		}
		int now = 0;
		int selfLoop = 0;
		for (int i = 0; i < p; i++) {
			if (now == i) selfLoop++;
			now = (now + k) % p;
		}

		g = new ArrayList[p];
		for (int i = 0; i < p; i++)
			g[i] = new ArrayList<Integer>();

		long res = 1;
		vis = new boolean[p];
		for (long i = 0; i < p; i++) {
			int from = (int)((i * k) % p);
			g[from].add((int)i);
		}

		for (int from = 0; from < p; from++) {
			if (vis[from]) continue;
			int x = from;
			for (int size = 1; size < p; size++) {
				vis[x] = true;
				x = g[x].get(0);
				if (x == from) {
					res = (res * (size == 1 ? selfLoop : p)) % MOD;
					break;
				}
			}
		}
		System.out.println(res);
	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		solve();
	}

	public static void main(String[] args) {
		new B().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;

import java.util.*;
import java.io.*;

@SuppressWarnings("unused")
public class Main {
    public static void main(String[] args) throws IOException {
        new Main().run();
    }

    BufferedReader in;
    PrintWriter out;
    StringTokenizer st = new StringTokenizer("");

    private void run() throws IOException {
        if (new File("input.txt").exists())
            in = new BufferedReader(new FileReader("input.txt"));
        else
            in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        solve();
        in.close();
        out.close();
    }

    long MOD = 1;

    long AMOD = 1000 * 1000 * 1000 + 7L;

    private void solve() throws IOException {

        long time = currentTimeMillis();

        int p = nextInt();
        MOD = p;
        int k = nextInt();
        boolean u[] = new boolean[p];
        int cnt = 0;
        for (int i = 1; i < p; i++) {
            if (!u[i]) {
                cnt++;
                int cur = i;
//              System.err.println("i " + i);
                while (true) {
                    if (u[cur])
                        break;
                    u[cur] = true;
                    long x = cur * (long)k;
                    x %= p;
                    cur = (int)x;
//                  System.err.println("cur " + cur);
                }
            }
        }

//      System.err.println(cnt);

        long ans = 0;
        if (k == 0) {
            ans = apow(p, p - 1);
        }
        else if (k == 1) {
            ans = apow(p, p);
        }
        else {
            int y = (p - 1) / cnt;
//          System.err.println(y);
            long fac[] = new long[cnt + 1];
            long rfac[] = new long[cnt + 1];
            fac[0] = 1L;

            long ypow[] = new long[cnt + 1];
            long cpow[] = new long[cnt + 1];

            for (int i = 0; i < cnt; i++) {
                fac[i + 1] = fac[i] * (i + 1L);
                fac[i + 1] %= AMOD;
            }
            for (int i = 0; i <= cnt; i++) {
                rfac[i] = apow(fac[i], AMOD - 2);
            }

            ypow[0] = 1;
            cpow[0] = 1;
            for (int i = 1; i <= cnt; i++) {
                ypow[i] = ypow[i - 1] * y % AMOD;
                cpow[i] = cpow[i - 1] * cnt % AMOD;
            }
//          System.err.println("here");

            for (int i = 0; i <= cnt; i++) {
                long cans = fac[cnt];
//              cans *= fac[cnt];
//              cans %= AMOD;
                cans *= rfac[i];
//              cans *= apow(fac[i], AMOD - 2);
                cans %= AMOD;
//              cans *= apow(fac[i], AMOD - 2);
//              cans %= AMOD;
                cans *= rfac[cnt - i];
//              cans *= apow(fac[cnt - i], AMOD - 2);
                cans %= AMOD;
//              cans *= apow(fac[cnt - i], AMOD - 2);
//              cans %= AMOD;

//              System.err.println(cans);
                cans *= ypow[cnt - i];
//              cans *= apow(y, (cnt - i));
                cans %= AMOD;
                cans *= cpow[cnt - i];
//              cans *= apow(cnt, (cnt - i));
                cans %= AMOD;
//              System.err.println(cans);
                ans += cans;
                ans %= AMOD;
            }
//          System.err.println(apow(7, 7));
//          System.err.println(fac[2]);
//          System.err.println(apow(2, 10));

        }

        out.println(ans);

//      System.err.println(currentTimeMillis() - time);

    }

    long pow(long a, long b) {
        if (b == 0)
            return 1L;
        long x = pow(a, b / 2);
        x = (x * x % MOD);
        if (b % 2 == 1) {
            x = (x * a % MOD);
        }
        return x;
    }

    long apow(long a, long b) {
        if (b == 0)
            return 1L;
        long x = apow(a, b / 2);
        x = (x * x % AMOD);
        if (b % 2 == 1) {
            x = (x * a % AMOD);
        }
        return x;
    }

    void chk(boolean b) {
        if (b)
            return;
        System.out.println(new Error().getStackTrace()[1]);
        exit(999);
    }
    void deb(String fmt, Object... args) {
        System.out.printf(Locale.US, fmt + "%n", args);
    }
    String nextToken() throws IOException {
        while (!st.hasMoreTokens())
            st = new StringTokenizer(in.readLine());
        return st.nextToken();
    }
    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
    String nextLine() throws IOException {
        st = new StringTokenizer("");
        return in.readLine();
    }
    boolean EOF() throws IOException {
        while (!st.hasMoreTokens()) {
            String s = in.readLine();
            if (s == null)
                return true;
            st = new StringTokenizer(s);
        }
        return false;
    }
}

import java.util.*;
import java.io.*;

public class Main {

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws IOException {

        StringTokenizer st = new StringTokenizer(br.readLine());

        long p=Long.parseLong(st.nextToken());
        long k=Long.parseLong(st.nextToken());
        long mod=1000000007L;
        long fyz=1L;
        if(k==1L)
        {

            for(long i=0L;i<p;i++)
            {
                fyz*=p;
                fyz%=mod;
            }

            System.out.println(fyz);

        }
        if(k==0L)
        {
            for(long i=0L;i<p-1;i++)
            {
                fyz*=p;
                fyz%=mod;
            }

            System.out.println(fyz);

        }

        if(k!=1L && k!=0L)
        {
            long d;
            long kk=k;
            for(d=2;;d++)
            {
                kk*=k;
                kk%=p;
                if(kk==1L)
                    break;
            }
            long qq=(p-1)/d;
            for(long i=0L;i<qq;i++)
            {
                fyz*=p;
                fyz%=mod;
            }
            System.out.println(fyz);

        }

    }
}

import java.io.*;
import java.util.*;

public class Main {

    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    static PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException{

        long p=Long.parseLong(Read.consoleRead());
        long k=Long.parseLong(Read.consoleRead());
        long mod=1000000007L;
        long fyz=1L;
        if(k==1L)
        {

            for(long i=0L;i<p;i++)
            {
                fyz*=p;
                fyz%=mod;
            }

            pw.println(fyz);

        }
        if(k==0L)
        {
            for(long i=0L;i<p-1;i++)
            {
                fyz*=p;
                fyz%=mod;
            }

            pw.println(fyz);

        }

        if(k!=1L && k!=0L)
        {
            long d;
            long kk=k;
            for(d=2;;d++)
            {
                kk*=k;
                kk%=p;
                if(kk==1L)
                    break;
            }
            long qq=(p-1)/d;
            for(long i=0L;i<qq;i++)
            {
                fyz*=p;
                fyz%=mod;
            }
            pw.println(fyz);

        }

        pw.flush();

    }
}
class Read {
    static private StringTokenizer st= new StringTokenizer("");

    static private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static String consoleRead() throws IOException{

        if(st.countTokens()==0)
            st=new StringTokenizer(br.readLine());

        return st.nextToken();

    }

}

import java.io.*;
import java.util.*;
import java.math.*;

public class B implements Runnable {
	private static BufferedReader in;
	private static PrintWriter out;
	private static StringTokenizer st;
	private static Random rnd;

	private void solve() throws IOException {
		int p = nextInt();
		int k = nextInt();
		out.println(solveSmart(p, k));
	}

	private long solveSmart(int p, int k) {
		final long MODULO = 1000000000 + 7;
		int cycles = getCycles(p, k);
		if (k == 1)
			++cycles;
		long result = 1;
		for (int i = 0; i < cycles - 1; i++)
			result = (result * p) % MODULO;
		return result;
	}

	private int getCycles(int p, int k) {
		boolean[] used = new boolean[p];
		int result = 0;
		for (int i = 0; i < p; i++) {
			if (!used[i]) {
				++result;
				int j = i;
				while (!used[j]) {
					used[j] = true;
					j = (int) (((long) j * k) % p);
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		new B().run();
	}

	public void run() {
		try {
			final String className = this.getClass().getName().toLowerCase();

			try {
				in = new BufferedReader(new FileReader(className + ".in"));
				out = new PrintWriter(new FileWriter(className + ".out"));
				// in = new BufferedReader(new FileReader("input.txt"));
				// out = new PrintWriter(new FileWriter("output.txt"));
			} catch (FileNotFoundException e) {
				in = new BufferedReader(new InputStreamReader(System.in));
				out = new PrintWriter(System.out);
			}

			rnd = new Random();

			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(42);
		}
	}

	private String nextToken() throws IOException {
		while (st == null || !st.hasMoreTokens()) {
			String line = in.readLine();

			if (line == null)
				return null;

			st = new StringTokenizer(line);
		}

		return st.nextToken();
	}

	private int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	private long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	private double nextDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
//     Test.testing();
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.flush();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    ArrayList<ArrayList<Integer>> gr1;
    ArrayList<ArrayList<Integer>> gr2;
    boolean[] visit;
    //

    public void solve() {
        int[] l = io.readIntArray();
        long p = l[0], k = l[1];
        long res = 1;
        long mod = 1000_000_007;
        visit = new boolean[(int) p];
        for (int i = 1; i < p; i++) {
            int h = i;
            boolean need = false;
            while (!visit[h]) {
                need = true;
                visit[h] = true;
                h = (int) (k * h % p);
            }
            if(need) res = (res * p) % mod;
        }
        if(k==1)res = (res*p)%mod;
        io.writeLine(res + "");
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long readLong() {
        return Long.parseLong(this.readLine());
    }
    public int readInt() {
        return Integer.parseInt(this.readLine().trim());
    }
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split(" ");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 *
 * @author pttrung
 */
public class B_Round_334_Div1 {

	public static long MOD = 1000000007;

	public static void main(String[] args) throws FileNotFoundException {
		// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
		// "output.txt")));
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();
		int p = in.nextInt();
		int k = in.nextInt();
		if (k != 0) {
			long[] l = new long[p + 1];
			int[] check = new int[p];
			check[0] = 1;
			l[1]++;
			for (int i = 1; i < p; i++) {
				if (check[i] == 0) {
					long v = i;
					int c = 0;
					do {
						check[(int)v] = -1;
						c++;
						v = (k * v) % p;
					} while (check[(int)v] == 0);
					check[i] = c;
					l[c]++;
				}
			}
			// System.out.println(Arrays.toString(l) + " " +
			// Arrays.toString(check));
			long[] pre = new long[p + 1];
			pre[0] = 1;
			for (int i = 1; i < pre.length; i++) {
				pre[i] = (long) i * pre[i - 1];
				pre[i] %= MOD;
			}
			long result = 1;
			for (int i = 0; i < p; i++) {
				if (check[i] != -1) {
					long total = 0;
					for (int j = 1; j * j <= check[i]; j++) {
						if (check[i] % j == 0) {
							int o = check[i] / j;
							total += (l[j] * j) % MOD;
							total %= MOD;
							if (o != j) {
								total += (l[o] * o) % MOD;
								total %= MOD;
							}
						}
					}
					// System.out.println(total + " " + i);
					result *= total;
					result %= MOD;
				}
			}
			out.println(result);
		} else {
			out.println(pow(p, p - 1));
		}
		// out.println(cal(0,new int[p], k));
		out.close();
	}

	public static int cal(int index, int[] data, int k) {
		if (index == data.length) {
			int p = data.length;
			boolean ok = true;
			for (int i = 0; i < p; i++) {
				if ((k * data[i]) % p != data[(i * k) % p]) {
					ok = false;
					break;
				}
			}
			if (ok) {
				// System.out.println(Arrays.toString(data));
				return 1;
			}
			return 0;
		}
		int result = 0;
		for (int i = 0; i < data.length; i++) {
			data[index] = i;
			result += cal(index + 1, data, k);
		}
		return result;
	}

	public static int[] KMP(String val) {
		int i = 0;
		int j = -1;
		int[] result = new int[val.length() + 1];
		result[0] = -1;
		while (i < val.length()) {
			while (j >= 0 && val.charAt(j) != val.charAt(i)) {
				j = result[j];
			}
			j++;
			i++;
			result[i] = j;
		}
		return result;

	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	public static int digit(long n) {
		int result = 0;
		while (n > 0) {
			n /= 10;
			result++;
		}
		return result;
	}

	public static double dist(long a, long b, long x, long y) {
		double val = (b - a) * (b - a) + (x - y) * (x - y);
		val = Math.sqrt(val);
		double other = x * x + a * a;
		other = Math.sqrt(other);
		return val + other;

	}

	public static class Point implements Comparable<Point> {

		int x, y;

		public Point(int start, int end) {
			this.x = start;
			this.y = end;
		}

		@Override
		public int hashCode() {
			int hash = 5;
			hash = 47 * hash + this.x;
			hash = 47 * hash + this.y;
			return hash;
		}

		@Override
		public boolean equals(Object obj) {
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			final Point other = (Point) obj;
			if (this.x != other.x) {
				return false;
			}
			if (this.y != other.y) {
				return false;
			}
			return true;
		}

		@Override
		public int compareTo(Point o) {
			return x - o.x;
		}
	}

	public static class FT {

		long[] data;

		FT(int n) {
			data = new long[n];
		}

		public void update(int index, long value) {
			while (index < data.length) {
				data[index] += value;
				index += (index & (-index));
			}
		}

		public long get(int index) {
			long result = 0;
			while (index > 0) {
				result += data[index];
				index -= (index & (-index));
			}
			return result;

		}
	}

	public static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	public static long pow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b == 1) {
			return a;
		}
		long val = pow(a, b / 2);
		if (b % 2 == 0) {
			return val * val % MOD;
		} else {
			return val * (val * a % MOD) % MOD;

		}
	}

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("input.txt"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public String nextLine() {
			st = null;
			try {
				return br.readLine();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}

import java.util.*;
public class b {
    public static long mod = 1000000007;
    public static void main(String[] args){
        Scanner br = new Scanner(System.in);
        int p = br.nextInt();
        long k = br.nextInt();

        int[] out = new int[p];
        for(int i = 0;i<p;i++){
            out[(int)((i*k)%p)] = i;
        }

        if(k == 0){
            System.out.println(pow(p, p-1, mod));
        }
        else if(k == 1){
            System.out.println(pow(p, p, mod));
        }
        else{

            int cycles = 0;
            boolean[] done = new boolean[p];
            for(int i = 0;i<p;i++){
                if(!done[i]){
                    cycles++;
                    int cur = i;
                    while(!done[cur]){

                        done[cur] = true;
                        cur = out[cur];
                    }
                }
            }
            System.out.println(pow(p, cycles-1, mod));
        }
    }
    public static long pow(long base, int pow, long mod){
        if(pow == 0) return 1;

        long res = pow(base, pow/2, mod);
        res = (res*res)%mod;
        if(pow%2 == 1){
            res = (res*base)%mod;
        }
        return res;
    }
}

// package codeforces.cf3xx.cf334.div1;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

/**
 * Created by hama_du on 2016/08/17.
 */
public class B {
    private static final long MOD = (long)1e9+7;

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n = in.nextInt();
        int k = in.nextInt();

        int mul;
        if (k >= 2) {
            int cnt = 0;
            boolean[] visited = new boolean[n];
            int head = 1;
            while (!visited[head]) {
                visited[head] = true;
                cnt++;
                head = (int) (((long) head) * k % n);
            }
            mul = (n-1) / cnt;
        } else if (k == 1) {
            mul = n;
        } else {
            mul = n-1;
        }

        long ans = 1;
        for (int g = 0 ; g < mul ; g++) {
            ans *= n;
            ans %= MOD;
        }

        out.println(ans);
        out.flush();
    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        private int[] nextInts(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }

        private int[][] nextIntTable(int n, int m) {
            int[][] ret = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    ret[i][j] = nextInt();
                }
            }
            return ret;
        }

        private long[] nextLongs(int n) {
            long[] ret = new long[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextLong();
            }
            return ret;
        }

        private long[][] nextLongTable(int n, int m) {
            long[][] ret = new long[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    ret[i][j] = nextLong();
                }
            }
            return ret;
        }

        private double[] nextDoubles(int n) {
            double[] ret = new double[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextDouble();
            }
            return ret;
        }

        private int next() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public char nextChar() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            if ('a' <= c && c <= 'z') {
                return (char) c;
            }
            if ('A' <= c && c <= 'Z') {
                return (char) c;
            }
            throw new InputMismatchException();
        }

        public String nextToken() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            StringBuilder res = new StringBuilder();
            do {
                res.append((char) c);
                c = next();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public int nextInt() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = next();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = next();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            long sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = next();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = next();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            return Double.valueOf(nextToken());
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }

    static void debug(Object... o) {
        System.err.println(Arrays.deepToString(o));
    }
}

import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.IOException;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Artem Gilmudinov
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Reader in = new Reader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task {
        public void solve(int testNumber, Reader in, PrintWriter out) {
            int p, k;
            p = in.ni();
            k = in.ni();
            long mod = 1_000_000_007;
            if (k == 0) {
                out.println(Utils.binpow(p, p - 1, mod));
            } else if (k == 1) {
                out.println(Utils.binpow(p, p, mod));
            } else {
                int[] cntOfCycles = new int[p];
                boolean[] used = new boolean[p];
                for (int i = 0; i < p; i++) {
                    if (used[i]) {
                        continue;
                    }
                    int j = i;
                    int len = 0;
                    while (!used[j]) {
                        used[j] = true;
                        j = Utils.mul(j, k, p);
                        ++len;
                    }
                    ++cntOfCycles[len];
                }
                long[] dp = new long[p];
                for (int i = 1; i < p; i++) {
                    for (int j = 1; j * i < p; j++) {
                        dp[j] = (dp[j] + cntOfCycles[i] * i) % mod;
                    }
                }
                long ans = 1;
                for (int i = 1; i < p; i++) {
                    ans = (ans * dp[i]) % mod;
                }
                out.println(ans);
            }
        }

    }

    static class Reader {
        private BufferedReader in;
        private StringTokenizer st = new StringTokenizer("");
        private String delim = " ";

        public Reader(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
        }

        public String next() {
            if (!st.hasMoreTokens()) {
                st = new StringTokenizer(rl());
            }
            return st.nextToken(delim);
        }

        public String rl() {
            try {
                return in.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public int ni() {
            return Integer.parseInt(next());
        }

    }

    static class Utils {
        public static int mul(int a, int b, long mod) {
            return (int) (((long) a) * b % mod);
        }

        public static long binpow(long a, long pow, long mod) {
            if (pow == 0) {
                return 1;
            }
            long res = binpow(a, pow / 2, mod);
            if (pow % 2 == 0) {
                return (res * res) % mod;
            } else {
                return (((res * res) % mod) * a) % mod;
            }
        }

    }
}

//package round334;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class B {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int mod = 1000000007;
		int p = ni(), K = ni();
		if(K == 0){
			out.println(pow(p, p-1, mod));
		}else if(K == 1){
			out.println(pow(p, p, mod));
		}else{
			DJSet ds = new DJSet(p);
			for(int i = 1;i < p;i++){
				ds.union(i, (int)((long)i*K%p));
			}
			out.println(pow(p, ds.count()-1, mod));
		}
	}

	public static class DJSet {
		public int[] upper;

		public DJSet(int n) {
			upper = new int[n];
			Arrays.fill(upper, -1);
		}

		public int root(int x) {
			return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
		}

		public boolean equiv(int x, int y) {
			return root(x) == root(y);
		}

		public boolean union(int x, int y) {
			x = root(x);
			y = root(y);
			if (x != y) {
				if (upper[y] < upper[x]) {
					int d = x;
					x = y;
					y = d;
				}
				upper[x] += upper[y];
				upper[y] = x;
			}
			return x == y;
		}

		public int count() {
			int ct = 0;
			for (int u : upper)
				if (u < 0)
					ct++;
			return ct;
		}
	}

	public static long pow(long a, long n, long mod) {
		//		a %= mod;
		long ret = 1;
		int x = 63 - Long.numberOfLeadingZeros(n);
		for (; x >= 0; x--) {
			ret = ret * ret % mod;
			if (n << 63 - x < 0)
				ret = ret * a % mod;
		}
		return ret;
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new B().run(); }

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

import java.util.Scanner;

public class Mod
{
	public static long exp_func_mod(long pow, long base, long mod)
	{
		if(pow == 1) return base % mod;
		else if(pow%2 == 0)
			return (exp_func_mod(pow/2, base, mod)*exp_func_mod(pow/2, base, mod))%mod;
		else
			return (base*exp_func_mod(pow-1, base, mod))%mod;
	}

	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		long p = input.nextInt();
		long k = input.nextInt();
		input.close();
		long modulus = 1000000000 + 7;

		if(k == 0)
		{
		long result = exp_func_mod(p-1, p, modulus);
		System.out.println(result);
		}
		else if(k == 1)
		{
		long result = exp_func_mod(p, p, modulus);
		System.out.println(result);
		}
		else
		{
		long cycle_length = 1;
		long val = k;
		while(cycle_length < p && val != 1)
		{
			val = (val*k)%p;
			cycle_length++;
		}
		long cycles = (p-1)/cycle_length;
		long result = exp_func_mod(cycles, p, modulus);
		System.out.println(result);
		}
	}
}

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class Round334B {

	public static final int mod = (int)1e9+7;
	public static LinkedList<Integer>[] adj;

	public static boolean[] visited;

	public static void dfs(int curr) {
		visited[curr] = true;
		for(Integer x : adj[curr]) {
			if(!visited[x]) {
				dfs(x);
			}
		}
	}

	public static void IterativeDfs(int curr) {
		while(!visited[curr]) {
			visited[curr] = true;
			for(Integer x : adj[curr]) {
				if(!visited[x]) {
					curr = x;
				}
			}
		}
	}

	public static int components() {
		int n = adj.length;
		int ans = 0;
		visited = new boolean[n];
		for(int i = 1; i < n; i++) {
			if(!visited[i]) {
				IterativeDfs(i);
				ans++;
			}
		}
		return ans;
	}

	public static void solve() {
		int p = s.nextInt();
		int k = s.nextInt();
		adj = new LinkedList[p];
		for(int i = 0; i < p; i++) {
			adj[i] = new LinkedList<Integer>();
		}
		for(int i = 1; i < p; i++) {
			long val = (long)k * (long)i;
			val %= p;
			adj[(int)val].add(i);
		}
		int pow = components();
		if(k == 1) {
			pow++;
		}
		long ans = fast(p, pow);
		out.println(ans);
	}

	public static long fast(long a, int n) {
		if(n == 1) {
			return a;
		}
		long ans = fast(a, n/2);
		ans = ans * ans;
		ans %= mod;
		if(n % 2 == 1) {
			ans = ans * a;
			ans %= mod;
		}
		return ans;
	}

	public static void main(String[] args) {
		new Thread(null, null, "Naman", 1 << 27) {
            public void run() {
                try {
                	out = new PrintWriter(new BufferedOutputStream(System.out));
            		s = new FastReader();
            		solve();
            		out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.exit(1);
                }
            }
        }.start();
	}

	public static FastReader s;
	public static PrintWriter out;

	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return str;
		}
	}

}

import java.io.*;
import java.util.*;

public class modarith {
  private static InputReader in;
  private static PrintWriter out;
  public static int mod = 1000000007;

  public static void main(String[] args) throws IOException {
    in = new InputReader(System.in);
    out = new PrintWriter(System.out, true);

    long p = in.nextInt(), k = in.nextInt();
    if (k == 1) {
      long res = 1;
      for(int j = 0; j < p; j++) res = (res * p) % mod;
      out.println(res);
      out.close();
      System.exit(0);
    }
    int cyclen = 0;
    long cur = k;
    do {
      ++cyclen;
      cur = (cur * k) % p;
    } while (cur != k);
    if ((p-1) % cyclen != 0) {
      out.println("AHGIHAG");
      System.exit(1);
    }
    long left = (p-1)/cyclen;
    long res = 1;
    while (left-->0) res = (res * p) % mod;
    out.println(res);
    out.close();
    System.exit(0);
  }

  static class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
      reader = new BufferedReader(new InputStreamReader(stream), 32768);
      tokenizer = null;
    }

    public String next() {
      while (tokenizer == null || !tokenizer.hasMoreTokens()) {
        try {
          tokenizer = new StringTokenizer(reader.readLine());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      return tokenizer.nextToken();
    }

    public int nextInt() {
      return Integer.parseInt(next());
    }
  }

}

import java.io.*;
import java.util.*;
import java.math.*;
import java.util.concurrent.*;

public final class ma
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Random rnd=new Random();
	static long x_mod=(long)(1e9+7);

	static long pow(long a,long b,long mod)
	{
		long x=1,y=a;

		while(b>0)
		{
			if(b%2==1)
			{
				x=(x*y)%mod;
			}

			y=(y*y)%mod;b=b/2;
		}

		return x;
	}

    public static void main(String args[]) throws Exception
    {
		int p=sc.nextInt(),k=sc.nextInt(),tot=p-1;

		List<Integer> list=new ArrayList<>();

		for(int i=1;i*i<=tot;i++)
		{
			if(tot%i==0)
			{
				list.add(i);

				if(i!=(tot/i))
				{
					list.add(tot/i);
				}
			}
		}

		int min=Integer.MAX_VALUE;

		for(int x:list)
		{
			long now=pow(k,x,p)%p;

			if(now==1)
			{
				min=Math.min(min,x);
			}
		}

		long res=pow(p,(tot/min),x_mod);

		if(k==1)
		{
			res=(res*p)%x_mod;
		}

		else if(k==0)
		{
			res=pow(p,p-1,x_mod);
		}

		out.println(res);out.close();
    }
}
class FastScanner
{
    BufferedReader in;
    StringTokenizer st;

    public FastScanner(BufferedReader in) {
        this.in = in;
    }

    public String nextToken() throws Exception {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

	public String next() throws Exception {
		return nextToken().toString();
	}

    public int nextInt() throws Exception {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws Exception {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }
}

import java.io.*;
import java.util.*;

public class B {

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;
    boolean eof;

    static final int MOD = 1_000_000_007;

    void solve() throws IOException {
        int p = nextInt();
        int k = nextInt();

        int ret = 1;

        if (k == 0) {
            for (int i = 1; i < p; i++) {
                ret = (int) ((long) ret * p % MOD);
            }
        } else if (k == 1) {
            for (int i = 0; i < p; i++) {
                ret = (int) ((long) ret * p % MOD);
            }
        } else {
            int len = 1;
            for (int v = k; v != 1; v = (int) ((long) v * k % p)) {
                len++;
            }
            int cycles = (p - 1) / len;
            for (int i = 0; i < cycles; i++) {
                ret = (int) ((long) ret * p % MOD);
            }
        }

        out.println(ret);
    }

    B() throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    public static void main(String[] args) throws IOException {
        new B();
    }

    String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return null;
            }
        }
        return st.nextToken();
    }

    String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            eof = true;
            return null;
        }
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;

public class C334D1BModAri {
	static int P, K;
	static long M = 1000000007l;
	static int[] A;
	public static void main(String[] args){
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		try {
			String[] chks  = br.readLine().split(" ");
			P =  Integer.parseInt(chks[0]);
			K = Integer.parseInt(chks[1]);
//			prln(P + " " + K);
			A = new int[P];
			A[0] = 0;
			if(K == 0){
				prln(pw((long)P, (long) P-1, M)+"");
			}else if(K == 1){
				prln(pw((long)P, (long) P, M)+"");
			}	else {
				for(int i =1 ; i < P; i++){
					A[i] = (int) (((long)K * (long)i)%(long)P);
				}
				Stack<Integer> S = new Stack<>();
				ArrayList<Integer> path = new ArrayList<>();
				boolean[][] vs = new boolean[P][2];
				for(int i = 1; i < P; i++){
					S.add(i);
				}
				int x = 0;
				int cmp = 0;
				while(!S.isEmpty()){
					x = S.pop();
//					if(x < 0 || x > P){
//						System.out.println("here i come" + x);
//						System.exit(0);
//					}
					if(vs[x][0]){
						for(int i: path){
							vs[i][0] = true;
						}
						path.clear();
					} else if(vs[x][1]) {
						cmp++;
						for(int i: path){
							vs[i][0] = true;
						}
						path.clear();
					} else {
						vs[x][1]= true;
						S.push(A[x]);
						path.add(x);
					}
				}
				prln( pw(P, cmp, M)+  "");
			}
 		} catch(IOException e){
			e.printStackTrace();
		}
	}

	static void prln(String s){
		System.out.println(s);
	}
	static long pw(long a, long b, long m){
		if(b == 1) return a;
		else {
			long x = pw(a, b>>1, m);
			x  = (x*x)%m;
			if((b&1) == 0){
				return x;
			}else {
				return (x*a) %m;
			}
		}
	}

}

import java.io.*;

public class Main {
    final static long mod = (long) 1e9 + 7;

    public static long pow(long x, long n) {
        long ans = 1;
        while(n != 0) {
            if(n%2 == 1)
                ans *= x;
                ans %= mod;
            n/= 2;
            x *= x;
            x %= mod;
        }
        return ans % mod;
    }

	public static void main (String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input = bf.readLine().split(" ");
		long p = Integer.parseInt(input[0]);
		long k = Integer.parseInt(input[1]);
		long order = 1;
		long temp = k;

		if (k == 0)
		    System.out.println((int) pow(p, p - 1));
		else {
    	    while (order < p) {
    	        if(temp == 1)
    	            break;
    	        temp = ((k % p) * (temp % p)) % p;
    	        order++;
    	    }
    	   if (k == 1)
		        System.out.println(((pow(p,p))));
		    else
		    System.out.println(((pow(p, (p - 1)/order))));
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class MoodularArithmetic {

	public static void main(String[] args) throws IOException {

		Scanner sc = new Scanner(System.in);

		int p = sc.nextInt();

		int k = sc.nextInt();

		UnionFind uf = new UnionFind(p);

		for (int i = 0; i < p; i++) {
			uf.unionSet(i,(int) (1L *k * i % p));
		}

		if(k == 0)
			System.out.println(modPow(p, p-1, (int) 1e9 + 7));
		else if(k == 1)
			System.out.println(modPow(p, p, (int) 1e9 + 7));
		else
			System.out.println(modPow(p, uf.numSets-1, (int) 1e9 + 7));

	}

	static long modPow(long a, int e, int mod)	// O(log e)
	{
		a %= mod;
		long res = 1;
		while(e > 0)
		{
			if((e & 1) == 1)
				res = (res * a) % mod;
			a = (a * a) % mod;
			e >>= 1;
		}
		return res;
}

	static public class UnionFind {
		int[] p, rank, setSize;
		int numSets;

		public UnionFind(int N)
		{
			p = new int[numSets = N];
			rank = new int[N];
			setSize = new int[N];
			for (int i = 0; i < N; i++) {  p[i] = i; setSize[i] = 1; }
		}

		public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }

		public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }

		public void unionSet(int i, int j)
		{
			if (isSameSet(i, j))
				return;
			numSets--;
			int x = findSet(i), y = findSet(j);
			if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
			else
			{	p[x] = y; setSize[y] += setSize[x];
				if(rank[x] == rank[y]) rank[y]++;
			}
		}

		public int numDisjointSets() { return numSets; }

		public int sizeOfSet(int i) { return setSize[findSet(i)]; }
	}

	static class Scanner

	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-')
			{
				neg = true;
				start++;
			}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else
				{
					sb.append(x.charAt(i));
					if(dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}

		public boolean ready() throws IOException {return br.ready();}

	}
}

import java.util.*;

public class Solution{
	private static final int MOD = 1000000007;

	public static void main(String[] args){
		Scanner scanner = new Scanner(System.in);

		int p = scanner.nextInt();
		int k = scanner.nextInt();

		if (k == 0){
			System.out.println(pow(p, p-1));
			return;
		}

		if (k == 1){
			System.out.println(pow(p, p));
			return;
		}

		int i=1;
		long curr = k;

		while (curr != 1){
			i++;
			curr = (curr * k) % p;
		}

		long sol = pow(p, (p-1)/i);

		System.out.println(sol);
	}

	private static long pow(long base, long exp){
		long sol = 1;

		for (int i=0; i<exp; i++){
			sol = (sol * base) % MOD;
		}

		return sol;
	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author xwchen
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public static int cnt;
        public static int N = 1000002;
        public static Edge[] edges = new Edge[1000000 * 2 + 5];
        public static int[] head = new int[N];
        public static boolean[] vis = new boolean[N];

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            long p = in.nextLong();
            long k = in.nextLong();
            long mod = 1000000007;

            Arrays.fill(head, -1);
            Arrays.fill(vis, false);
            for (int i = 0; i < N * 2; ++i) {
                edges[i] = new Edge();
            }
            cnt = 0;
            long ret = 1;
            for (int i = 1; i < p; ++i) {
                addEdge((int) (k * i % p), i);
                addEdge(i, (int) (k * i % p));
            }
            if (k == 0) {
                for (int i = 1; i < p; ++i) {
                    ret = ret * p % mod;
                }
                out.println(ret);
                return;
            } else if (k == 1) {
                for (int i = 0; i < p; ++i) {
                    ret = ret * p % mod;
                }
                out.println(ret);
                return;
            }
            int count = 0;
            for (int i = 1; i < p; ++i) {
                if (!vis[i]) {
                    dfs(i, i);
                    ++count;
                }
            }
            //out.println("p="+p+" cnt = "+count);
            for (int i = 0; i < count; ++i) {
                ret = ret * p % mod;
            }
            out.println(ret);
        }

        public static void dfs(int u, int pre) {
            vis[u] = true;
            for (int e = head[u]; e != -1; e = edges[e].pre) {
                int v = edges[e].v;
                if (!vis[v]) {
                    dfs(v, u);
                }
            }
        }

        public static void addEdge(int u, int v) {
            edges[cnt].u = u;
            edges[cnt].v = v;
            edges[cnt].pre = head[u];
            head[u] = cnt++;
        }

        class Edge {
            int u;
            int v;
            int pre;

        }

    }
}

import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;

public class Main{
   // static ArrayList[] a = new ArrayList[2000001];

    public void solve () throws FileNotFoundException  {

    	InputReader in = new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        long p = in.nextLong();
        long k = in.nextLong();
        long start = 1L;
        boolean visited[] = new boolean [(int) (p + 2)];
        visited[0] = true;
        long cnt = 0;
        for(int i = 1 ; i < p ; i++ ) {
        	if(!visited[i]) {
        		cnt ++;
        		visited[i] = true;
        		long can = i * k * 1L;
        		can %= p;
        		while(!visited[(int) can]) {
        			visited[(int)can] = true;
        			can *= k;
        			can %= p;
        		}
        	}
        }
        if(k == 1)
        	cnt ++;
        pw.println(modularExponentiation(p , cnt  , mod));
        pw.flush();
        pw.close();
    }
    public static void main(String[] args) throws Exception {

        new Thread(null,new Runnable() {
            public void run() {
                    try {
                        new Main().solve();
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
        },"1",1<<26).start();

    }

    static void debug(Object... o) {
        System.out.println(Arrays.deepToString(o));
        }

        static class InputReader
        {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }
        public int snext()
        {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars)
            {
                curChar = 0;
                try
                {
                    snumChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n)
        {
            int a[] = new int[n];
            for (int i = 0; i < n; i++)
            {
                a[i] = nextInt();
            }
            return a;
        }

        public String readString()
        {
            int c = snext();
            while (isSpaceChar(c))
            {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine()
        {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c)
        {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }
        public static long mod = 1000000007;
        public static int d;
        public static int p;
        public static int q;
        public void extended(int a,int b) {
            if(b==0) {
                d=a;
                p=1;
                q=0;
            }
            else
            {
                extended(b,a%b);
                int temp=p;
                p=q;
                q=temp-(a/b)*q;
            }
        }

        public static long binaryExponentiation(long x,long n)
        {
            long result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=result * x;
                x=x*x;
                n=n/2;
            }
            return result;
        }

        public static long[] shuffle(long[] a,Random gen)
        {
            int n = a.length;
            for(int i=0;i<n;i++)
            {
                int ind = gen.nextInt(n-i)+i;
                long temp = a[ind];
                a[ind] = a[i];
                a[i] = temp;
            }
            return a;
        }

        public static void swap(int a, int b){
            int temp = a;
            a = b;
            b = temp;
        }

        public static HashSet<Integer> primeFactorization(int n)
        {
            HashSet<Integer> a =new HashSet<Integer>();
            for(int i=2;i*i<=n;i++)
            {
                while(n%i==0)
                {
                    a.add(i);
                    n/=i;
                }
            }
            if(n!=1)
                a.add(n);
            return a;
        }

        public static void sieve(boolean[] isPrime,int n)
        {
            for(int i=1;i<n;i++)
                isPrime[i] = true;

            isPrime[0] = false;
            isPrime[1] = false;

            for(int i=2;i*i<n;i++)
            {
                if(isPrime[i] == true)
                {
                    for(int j=(2*i);j<n;j+=i)
                        isPrime[j] = false;
                }
            }
        }

        public static long GCD(long n,long m)
        {
            if(m==0)
                return n;
            else
                return GCD(m,n%m);
        }
        public static long LCM (long a,long b) {
            return ((a*b)/(GCD(a,b)));
        }

        static class pair implements Comparable<pair>
        {
            Integer x ;
            Integer y;

            pair(int x,int y)
            {
                this.x=x;
                this.y=y;
            }

            public int compareTo(pair o) {
                int result = x.compareTo(o.x);
                if(result==0)
                    result = y.compareTo(o.y);

                return result;
            }

            public String toString()
            {
                return x+" "+y;
            }

            public boolean equals(Object o)
            {
                if (o instanceof pair)
                {
                    pair p = (pair)o;
                    return p.x == x && p.y == y ;
                }
                return false;
            }
            public int hashCode()
            {
                return new Long(x).hashCode()*3 + new Integer(y).hashCode();

            }
        }
        public static int binaryExponentiation(int x,int n)
        {
            int result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=result * x;
                x=x*x;
                n=n/2;
            }
            return result;
        }

        public static int modularExponentiation(int x,int n,int M)
        {
            int result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=(result * x)%M;
                x=(x%M*x)%M;
                n=n/2;
            }
            return result;
        }

        public static long modularExponentiation(long x,long n,long M)
        {
            long result=1;
            while(n>0)
            {
                if(n % 2 ==1)
                    result=(result%M * x%M)%M;
                x=(x%M * x%M)%M;
                n=n/2;
            }
            return result;
        }

        public static long modInverse(int A,int M)
        {
            return modularExponentiation(A,M-2,M);
        }

        public static long modInverse(long A,long M)
        {
            return modularExponentiation(A,M-2,M);
        }
        static class Segment{
    		int seg[];
    		int lazy[];
    	    Segment (int n){
    			seg=new int[4*n];
    		}
    	    public void build(int node,int start,int end) {
    	    	if(start==end) {
    	    		seg[node]=0;
    	    		return ;
    	    	}
    	    	int mid=(start+end)/2;
    	    	build(2*node+1,start,mid);
    	    	build(2*node+2,mid+1,end);
    	    	seg[node]=seg[2*node+1]+seg[2*node+2];
    	    }
    	    public void update(int node,int start,int end,int id,int val) {
    	    	if(start==end) {
    	    		seg[node]=val;
    	    		return;
    	    	}
    	    	int mid=(start+end)/2;
    	    	if(id>=start && id<=mid) {
    	    		update(2*node+1,start,mid,id,val);
    	    	}
    	    	else
    	    		update(2*node+2,mid+1,end,id,val);
    	    	seg[node]=seg[2*node+1]+seg[2*node+2];
    	    }
    	    public int query(int node,int start,int end,int l,int r) {
    	    	if(l>end || r<start)
    	    		return 0;
    	    	if(start>=l && end<=r)
    	    		return seg[node];

    	    	int  mid=(start+end)/2;
    	    	return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r));
    	    }
    	    public void updateRange(int node,int start,int end,int l,int r,int val) {
    	    	if(lazy[node]!=0) {
    	    		if(start!=end) {
    	    			lazy[2*node+1]+=lazy[node];
    	    			lazy[2*node+2]+=lazy[node];
    	    		}
    	    		lazy[node]=0;
    	    	}
    	    	if(l>end || r<start)
    	    		return ;
    	    	if(start>=l && end<=r) {
    	    		seg[node]=(end-start+1)*val;
    	    		if(start!=end) {
    	    			lazy[2*node+1]+=val;
    	    			lazy[2*node+2]+=val;
    	    		}
    	    		lazy[node]=0;
    	    		return ;
    	    	}
    	    	int mid=(start+end)/2;
    	    	updateRange(2*node+1,start,mid,l,r,val);
    	    	updateRange(2*node+2,mid+1,end,l,r,val);
    	    	seg[node]=seg[2*node+1]+seg[2*node+2];
    	    }
    	    public int queryRange(int node,int start,int end,int l,int r) {
    	    	if(l>end || r<start)
    	    		return 0;
    	    	if(lazy[node]!=0) {
    	    		seg[node]=(end-start+1)*lazy[node];
    	    		if(start!=end) {
    	    			lazy[2*node+1]+=lazy[node];
    	    			lazy[2*node+2]+=lazy[node];
    	    		}
    	    		lazy[node]=0;
    	    	}
    	    	if(start>=l && end<=r)
    	    		return seg[node];

    	    	int  mid=(start+end)/2;
    	    	return (query(2*node+1,start,mid,l,r)+query(2*node+2,mid+1,end,l,r));
    	    }

    	}

}

import java.util.*;
import java.io.*;

public class B {
    FastScanner in;
    PrintWriter out;
    boolean[] used;
    long[] pow;
    static long p, k;
    final long MOD = (long) 1e9 + 7;

    public void dfs(long v) {
        used[(int) v] = true;
        if (!used[(int) ((k * v) % p)]) {
            dfs((k * v) % p);
        }
    }

    public void solve() throws IOException {
        p = in.nextInt();
        k = in.nextInt();
        used = new boolean[(int) p];
        pow = new long[(int) p + 1];
        pow[0] = 1;
        for (int i = 0; i < p; i++) {
            pow[i + 1] = (pow[i] * p) % MOD;
        }
        int ans = 0;
        for (int i = 1; i < p; i++) {
            if (!used[i]) {
                dfs(i);
                ans++;
            }
        }
        if (k == 1) {
            ans++;
        }
        out.println(pow[ans]);
    }

    public void run() {
        try {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
            solve();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }

    public static void main(String[] arg) {
        new B().run();
    }
}

//package ok;
import java.util.HashMap;
import java.util.Map;
import java.math.*;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;
import java.io.PrintWriter;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }
    static long p, K;
    static boolean vis[] = new boolean [1000100];
    static long MOD = (int)1e9 + 7;

    static class TaskE {
        public void solve(int testNumber, Scanner in, PrintWriter out) {
            p = in.nextInt();
            K = in.nextInt();
            long ans = 1;
            if(K == 0)
                for(int i = 1; i < p; i ++) ans = (ans * p) % MOD;
            else if(K == 1)
                for(int i = 1; i <= p; i ++) ans = (ans * p) % MOD;
            else {
                for(int i = 0; i <= p; i ++) vis[i] = false;
                long cnt = 0;
                for(int i = 1; i < p; i ++)
                    if(vis[i] == false) {
                        cnt ++;
                        for(int j = i; vis[j] == false; j = (int)(K * j % p) )
                            vis[j] = true;
                    }
                //out.printf("cnt = %d\n", cnt); out.flush();
                for(int i = 1; i <= cnt; i ++) ans = (ans * p) % MOD;
            }
            out.println(ans);
            out.flush();

        }
    }

    static class pii implements Comparable<pii> {
        int X, Y;
        pii() {
            this.X = 0;
            this.Y = 0;
        }
        pii(int X, int Y) {
            this.X = X;
            this.Y = Y;
        }
        public int compareTo(pii a) {
            if(this.X - a.X != 0) return this.X - a.X;
            else return this.Y - a.Y;
        }
    }
    static class Scanner {
        BufferedReader br;
        StringTokenizer st;

        public Scanner(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in));
            eat("");
        }

        private void eat(String s) {
            st = new StringTokenizer(s);
        }

        public String nextLine() {
            try {
                return br.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        public boolean hasNext() {
            while (!st.hasMoreTokens()) {
                String s = nextLine();
                if (s == null)
                return false;
                eat(s);
            }
            return true;
        }

        public String next() {
            hasNext();
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public BigInteger nextBigInteger() {
            return new BigInteger(next());
        }

        public int[] nextIntArray(int n) {
            int[] is = new int[n];
            for (int i = 0; i < n; i++) {
                is[i] = nextInt();
            }
            return is;
        }

        public long[] nextLongArray(int n) {
            long[] ls = new long[n];
            for (int i = 0; i < n; i++) {
                ls[i] = nextLong();
            }
            return ls;
        }

        public double[] nextDoubleArray(int n) {
            double[] ds = new double[n];
            for (int i = 0; i < n; i++) {
                ds[i] = nextDouble();
            }
            return ds;
        }

        public BigInteger[] nextBigIntegerArray(int n) {
            BigInteger[] bs = new BigInteger[n];
            for (int i = 0; i < n; i++) {
                bs[i] = nextBigInteger();
            }
            return bs;
        }

        public int[][] nextIntMatrix(int row, int col) {
            int[][] mat = new int[row][];
            for (int i = 0; i < row; i++) {
                mat[i] = nextIntArray(col);
            }
            return mat;
        }

        public long[][] nextLongMatrix(int row, int col) {
            long[][] mat = new long[row][];
            for (int i = 0; i < row; i++) {
                mat[i] = nextLongArray(col);
            }
            return mat;
        }

        public double[][] nextDoubleMatrix(int row, int col) {
            double[][] mat = new double[row][];
            for (int i = 0; i < row; i++) {
                mat[i] = nextDoubleArray(col);
            }
            return mat;
        }

        public BigInteger[][] nextBigIntegerMatrix(int row, int col) {
            BigInteger[][] mat = new BigInteger[row][];
            for (int i = 0; i < row; i++) {
                mat[i] = nextBigIntegerArray(col);
            }
            return mat;
        }
    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static MyScanner   in;
    static PrintWriter out;
//    static Timer timer = new Timer();

    public static void main(String[] args) throws IOException {
        in = new MyScanner();
        out = new PrintWriter(System.out, true);

        int n = in.nextInt();
        int k = in.nextInt();

        int cycles = k == 1 ? 1 : 0;
        boolean[] was = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (!was[i]) {
                paint(i, n, k, was);
                cycles++;
            }
        }

        out.println(pow(n, cycles - 1, (long) 1e9 + 7));
    }

    private static long pow(long x, int n, long MOD) {
        if (n == 0) return 1;
        if (n % 2 == 1) {
            return (x * pow(x, n - 1, MOD)) % MOD;
        } else {
            return pow((x * x) % MOD, n / 2, MOD);
        }
    }

    private static void paint(int i, int p, int k, boolean[] was) {
        if (was[i]) return;
        was[i] = true;
        paint((int) (((long) i * k) % p), p, k, was);
    }
}
class MyScanner {

    public static final String CP1251 = "cp1251";

    private final BufferedReader  br;
    private       StringTokenizer st;
    private       String          last;

    public MyScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public MyScanner(String path) throws IOException {
        br = new BufferedReader(new FileReader(path));
    }

    public MyScanner(String path, String decoder) throws IOException {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder));
    }

    String next() throws IOException {
        while (st == null || !st.hasMoreElements())
            st = new StringTokenizer(br.readLine());
        last = null;
        return st.nextToken();
    }

    String next(String delim) throws IOException {
        while (st == null || !st.hasMoreElements())
            st = new StringTokenizer(br.readLine());
        last = null;
        return st.nextToken(delim);
    }

    String nextLine() throws IOException {
        st = null;
        return (last == null) ? br.readLine() : last;
    }

    boolean hasNext() {
        if (st != null && st.hasMoreElements())
            return true;

        try {
            while (st == null || !st.hasMoreElements()) {
                last = br.readLine();
                st = new StringTokenizer(last);
            }
        }
        catch (Exception e) {
            return false;
        }

        return true;
    }

    String[] nextStrings(int n) throws IOException {
        String[] arr = new String[n];
        for (int i = 0; i < n; i++)
            arr[i] = next();
        return arr;
    }

    String[] nextLines(int n) throws IOException {
        String[] arr = new String[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextLine();
        return arr;
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    int[] nextInts(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextInt();
        return arr;
    }

    Integer[] nextIntegers(int n) throws IOException {
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextInt();
        return arr;
    }

    int[][] next2Ints(int n, int m) throws IOException {
        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextInt();
        return arr;
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    long[] nextLongs(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextLong();
        return arr;
    }

    long[][] next2Longs(int n, int m) throws IOException {
        long[][] arr = new long[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextLong();
        return arr;
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(next().replace(',', '.'));
    }

    double[] nextDoubles(int size) throws IOException {
        double[] arr = new double[size];
        for (int i = 0; i < size; i++)
            arr[i] = nextDouble();
        return arr;
    }

    double[][] next2Doubles(int n, int m) throws IOException {
        double[][] arr = new double[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextDouble();
        return arr;
    }

    boolean nextBool() throws IOException {
        String s = next();
        if (s.equalsIgnoreCase("true") || s.equals("1"))
            return true;

        if (s.equalsIgnoreCase("false") || s.equals("0"))
            return false;

        throw new IOException("Boolean expected, String found!");
    }
}

/*
 * k = 0, f(0) = 0, p^(p-1)
 * k = 1, p^p
 * k = 2, p
 *  p = 3, f(2x mod 3) = 2f(x) mod 3,
 *      f(1) = 1, f(2) = 2
 *      f(2) = 2, f(1) = 1
 *  p = 5, f(2x mod 5) = 2f(x) mod 5,
 *      f(1) = 1, f(2) = 2, f(3) = 3, f(4) = 4
 *      f(1) = 2, f(2) = ...
 * k = 3, p
 *  p = 5, f(3x mod 5) = 3f(x) mod 5,
 *      f(1) = 1, f(3) = 3, f(
 * k = 4, p*p
 *  p = 5, f(4x mod 5) = 4f(x) mod 5,
 *     f(1) = 1, f(4) = 4  f(2) = 1, f(3) =  ,
 *  p = 7, f(4x mod 7) = 4f(x) mod 7,
 *     f(1),f(4),f(2),   f(3)f(5)
 *
 * k = 5, p
 * k = 6, 1,6  2,5 3,4
 * /
 */
import java.util.Scanner;
import java.util.Arrays;
import static java.lang.Math.toIntExact;

public class D {
    private static class mergeSet {
        private int set_size;
        private int[] parent;

        mergeSet(int size) {
            set_size = size;
            parent = new int[size];
            Arrays.fill(parent, -1);
        }

        int find(int x) {
            if(parent[x] < 0) return x; else return find(parent[x]);
        }

        void merge(int x, int y) {
            int p = find(x);
            int q = find(y);
            if (p == q) {
                return;
            }
            parent[q] += parent[p];
            parent[p] = q;
        }

        int count() {
            int ans=0;
            for(int i=1;i<set_size;i++) {
                if(parent[i]<0) ans ++;
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        Scanner scanIn = new Scanner(System.in);
        int p = scanIn.nextInt();
        int k = scanIn.nextInt();
        int cluster;
        if (k <= 1) {
            cluster = p - 1 + k;
        } else {
            mergeSet m = new mergeSet(p);
            for(int i = 1;i < p;i ++) {
                long temp = i;
                temp *= k;
                temp %= p;
                m.merge(i, toIntExact(temp));
            }
            cluster = m.count();
        }
        long ans = p;
        final int MOD = 1000000007;
        for(int i=1;i<cluster;i++) {
            ans = (ans * p) % MOD;
        }
        System.out.println(ans);
    }
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class D
{
	String line;
	StringTokenizer inputParser;
	BufferedReader is;
	FileInputStream fstream;
	DataInputStream in;

	void openInput(String file)
	{

		if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
		else
		{
			try{

			fstream = new FileInputStream(file);
			in = new DataInputStream(fstream);
			is = new BufferedReader(new InputStreamReader(in));
			}catch(Exception e)
			{
				System.err.println(e);
			}
		}

	}

	void readNextLine()
	{
		try {
			line = is.readLine();
			if(line!=null)inputParser = new StringTokenizer(line, " ");
			//System.err.println("Input: " + line);
		} catch (IOException e) {
			System.err.println("Unexpected IO ERROR: " + e);
		}

	}

	int NextInt()
	{
		String n = inputParser.nextToken();
		int val = Integer.parseInt(n);

		//System.out.println("I read this number: " + val);
		return val;
	}

    double NextDouble()
    {
            String n = inputParser.nextToken();
            double val = Double.parseDouble(n);

            //System.out.println("I read this number: " + val);
            return val;
    }

	long NextLong()
    {
            String n = inputParser.nextToken();

            long val = Long.parseLong(n);

            return val;
    }

	String NextString()
	{
		String n = inputParser.nextToken();
		return n;
	}

	void closeInput()
	{
		try {
			is.close();
		} catch (IOException e) {
			System.err.println("Unexpected IO ERROR: " + e);
		}

	}

	public static void main(String [] argv)
	{
		String filePath=null;
		if(argv.length>0)filePath=argv[0];
		new D(filePath);
	}

	public D(String inputFile)
	{
		openInput(inputFile);
		//readNextLine();
		int T=1;//NextInt();
		StringBuilder sb = new StringBuilder();
		final int MOD=1000000007;
		for(int t=1; t<=T; t++)
		{
			readNextLine();
			int N=NextInt();
			int K=NextInt();
			long ret=1;
			if(K==1)
				ret = pow(N,N, MOD);
			else if(K==0)
				ret = pow(N,N-1, MOD);
			else
			{
				UF uf = new UF(N);
				for(int i=1; i<N; i++)
				{
					long a=(long)K*i;
					a%=N;
					uf.join((int)a, i);
				}

				HashSet<Integer>set = new HashSet<Integer>();
				for(int i=0; i<N; i++)
				{
					set.add(uf.getP(i));
				}
				ret=pow(N, set.size()-1, MOD);
			}
			sb.append(ret);
		}
		System.out.print(sb);

		closeInput();
	}
	private long pow(long b, long exponent, long MOD)
	{
	    long ret = 1;
	    while(exponent > 0)
	    {
	        if (exponent%2 == 1)
	           ret = (ret * b) % MOD;
	        exponent = exponent >> 1;
	        b = (b * b) % MOD;
	    }
	    return ret;
	}

	private class UF
	{
		int [] p;
		int [] s;
		int N;
		UF(int N)
		{
			this.N=N;
			s = new int[N];
			p = new int[N];
			for(int i=0; i<N; i++)
			{
				p[i]=i;
				s[i]=1;
			}
		}

		public void join(int a, int b)
		{

			int x=getP(a);
			int y=getP(b);

			if(x==y)return;
			if(s[x]>s[y])
			{
				int t=x;
				x=y;
				y=t;
			}
			p[x]=p[y];
			s[y]+=s[x];
		}

		public int getP(int a)
		{
			if(p[a]==a)return a;
			return p[a]=getP(p[a]);
		}

		public int getC(int x)
		{
			return s[getP(x)];
		}
	}

}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Div2_334_D
{
    static final int MOD = 1000000007;
    static int [] comp;
    public static long pow(int b, int exp) {
        if(exp==0)
            return 1;
        if(exp%2 == 1)
            return (b*1l*pow(b, exp-1))%MOD;
        long r = pow(b, exp/2)%MOD;
        return (r*r)%MOD;
    }
    public static void dfs(int i, int p, int k) {
        int next = (int) ((1l*k*i)%p);
        if(comp[next] == -1) {
            comp[next] = 1;
            dfs(next, p, k);
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        if(k == 0)
            System.out.println(pow(p, p-1));
        else if(k == 1)
            System.out.println(pow(p, p));
        else {
            comp = new int[p];
            for(int i = 1;i < p;i++)
                comp[i] = -1;
            int num = 0;
            for(int i = 1;i < p;i++) {
                if(comp[i] == -1) {
                    num++;
                    comp[i] = num;
                    dfs(i, p, k);
                    //System.out.println(ret);
                }
            }
            System.out.println(pow(p, num));
        }
    }
}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class MoodularArithmetic {

	static final long MOD = (long) 1e9 + 7;

	static long modPow(long base, long exp, long MOD) {
		long res = 1;
		while (exp > 0) {
			if ((exp & 1) != 0)
				res = (res * base) % MOD;
			base = (base * base) % MOD;
			exp >>= 1;
		}
		return res % MOD;
	}

	public static void main(String[] args) throws IOException {
		MyScanner sc = new MyScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int p = sc.nextInt(), k = sc.nextInt(), power;
		if (k == 0) {
			out.println(modPow(p, p - 1, MOD));
		} else if (k == 1) {
			out.println(modPow(p, p, MOD));
		} else {
			for (power = 1; true; power++)
				if (modPow(k, power, p) == 1)
					break;
			out.println(modPow(p, (p - 1) / power, MOD));
		}
		out.flush();
		out.close();
	}

	static class MyScanner {

		BufferedReader br;
		StringTokenizer st;

		MyScanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		MyScanner(String filename) throws IOException {
			br = new BufferedReader(new FileReader(new File(filename)));
		}

		String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		String nextLine() throws IOException {
			return br.readLine();
		}

		int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		long nextLong() throws IOException {
			return Long.parseLong(next());
		}

		boolean ready() throws IOException {
			return br.ready();
		}
	}
}

//package que_a;

import java.io.*;
import java.util.*;
import java.math.*;

public class utkarsh {

    InputStream is;
    PrintWriter out;

    long mod = (long) (1e9 + 7), inf = (long) (3e18);

    int pt[], z;

    int root(int x) {
        while(x != pt[x]) {
            pt[x] = pt[ pt[x] ];
            x = pt[x];
        }   return x;
    }

    void union(int x, int y) {
        int u = root(x);
        int v = root(y);
        if(u == v)  return;
        z--;
        pt[u] = v;
    }

    void solve() {
        int n = ni(), k = ni();
        if(k == 0)  out.println(mp(n, n-1));
        else if(k == 1) out.println(mp(n, n));
        else {
            pt = new int[n];
            for(int i = 0; i < n; i++)  pt[i] = i;
            z = n;
            for(int i = 0; i < n; i++) {
                union(i, (int)(1L * k * i % n));
            }
            out.println(mp(n, z-1));
        }
    }

    long mp(long b, long e) {
        long r = 1;
        while(e > 0) {
            if((e&1) == 1)  r = (r * b) % mod;
            b = (b * b) % mod;
            e >>= 1;
        }
        return r;
    }

    //---------- I/O Template ----------

    public static void main(String[] args) { new utkarsh().run(); }
    void run() {
        is = System.in;
        out = new PrintWriter(System.out);
        solve();
        out.flush();
    }

    byte input[] = new byte[1024];
    int len = 0, ptr = 0;

    int readByte() {
        if(ptr >= len) { ptr = 0;
            try { len = is.read(input); }
            catch(IOException e) { throw new InputMismatchException(); }
            if(len <= 0) { return -1; }
        } return input[ptr++];
    }
    boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
    int skip() {
        int b = readByte();
        while(b != -1 && isSpaceChar(b)) { b = readByte(); }
        return b;
    }

    char nc() { return (char)skip(); }
    String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
        return sb.toString();
    }
    String nLine() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
        return sb.toString();
    }
    int ni() {
        int n = 0, b = readByte();
        boolean minus = false;
        while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
        if(b == '-') { minus = true; b = readByte(); }
        if(b == -1) { return -1; }  //no input
        while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
        return minus ? -n : n;
    }
    long nl() {
        long n = 0L;    int b = readByte();
        boolean minus = false;
        while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
        if(b == '-') { minus = true; b = readByte(); }
        while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
        return minus ? -n : n;
    }

    double nd() { return Double.parseDouble(ns()); }
    float nf() { return Float.parseFloat(ns()); }
    int[] na(int n) {
        int a[] = new int[n];
        for(int i = 0; i < n; i++) { a[i] = ni(); }
        return a;
    }
    char[] ns(int n) {
        char c[] = new char[n];
        int i, b = skip();
        for(i = 0; i < n; i++) {
            if(isSpaceChar(b)) { break; }
            c[i] = (char)b; b = readByte();
        } return i == n ? c : Arrays.copyOf(c,i);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Agostinho Junior (junior94)
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}

	static class TaskB {
		public TaskB() {
		/*
		for (int p = 3; p <= 10; p++) if (XMath.isPrime(p)) {
			for (int k = 0; k < p; k++) {
				System.out.printf("p: %d, k: %d\n", p, k);
				printIn(p, k);
				System.out.println("\n================");
			}
			System.out.println("================");
		}*/
		}

		public void solve(int testNumber, InputReader in, OutputWriter out) {
			int p = in.readInt();
			int k = in.readInt();

			if (k == 0) {
				out.println(XMath.modPow(p, p - 1));
				return;
			}

			if (k == 1) {
				out.println(XMath.modPow(p, p));
				return;
			}

			int[] sizeCount = new int[p + 1];
			boolean[] visited = new boolean[p];
			Set<Integer> set = new HashSet<>();
			for (int i = 0; i < p; i++)
				if (!visited[i]) {
					int node = i;
					set.clear();
					while (!visited[node]) {
						set.add(node);
						visited[node] = true;
						node = (int) XMath.mod((long) node * k, p);
					}
					if (node != 0) {
						sizeCount[set.size()]++;
					}
				}

			long res = 1;

			for (int size = 1; size < sizeCount.length; size++) {
				res = XMath.mod(res * XMath.modPow(XMath.mod(size * sizeCount[size] + 1), sizeCount[size]));
			}

			out.println(res);
		}

	}

	static class InputReader {
		private BufferedReader input;
		private StringTokenizer line = new StringTokenizer("");

		public InputReader() {
			this(System.in);
		}

		public InputReader(InputStream in) {
			input = new BufferedReader(new InputStreamReader(in));
		}

		public InputReader(String s) {
			try {
				input = new BufferedReader(new FileReader(s));
			} catch (IOException io) {
				io.printStackTrace();
				System.exit(0);
			}
		}

		public void fill() {
			try {
				if (!line.hasMoreTokens()) {
					line = new StringTokenizer(input.readLine());
				}
			} catch (IOException io) {
				io.printStackTrace();
				System.exit(0);
			}
		}

		public int readInt() {
			fill();
			return Integer.parseInt(line.nextToken());
		}

	}

	static class OutputWriter {
		private PrintWriter output;

		public OutputWriter() {
			this(System.out);
		}

		public OutputWriter(OutputStream out) {
			output = new PrintWriter(out);
		}

		public OutputWriter(Writer writer) {
			output = new PrintWriter(writer);
		}

		public void println(Object o) {
			output.println(o);
		}

		public void close() {
			output.close();
		}

	}

	static class XMath {
		public static final long DEFAULT_MOD = (long) 1e9 + 7;
		public static long MOD = DEFAULT_MOD;

		public static long mod(long n, long MOD) {
			if (n < MOD) {
				if (n < 0) {
					return mod(MOD - mod(-n, MOD), MOD);
				}
				return n;
			}
			return n % MOD;
		}

		public static long mod(long n) {
			return mod(n, MOD);
		}

		public static long modPow(long x, long n, long mod) {
			long res = 1;
			x = mod(x, mod);
			while (n > 0) {
				if ((n & 1) > 0) {
					res = mod(res * x, mod);
				}
				x = mod(x * x, mod);
				n >>= 1;
			}
			return res;
		}

		public static long modPow(long x, long n) {
			return modPow(x, n, MOD);
		}

	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author AlexFetisov
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB_Function solver = new TaskB_Function();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB_Function {
        private static final int MOD = (int) 1e9 + 7;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int p = in.nextInt();
            int k = in.nextInt();
            if (k == 0) {
                out.println(IntegerUtils.pow(p, p - 1, MOD));
            } else if (k == 1) {
                out.println(IntegerUtils.pow(p, p, MOD));
            } else {
                int max = p - 1;
                for (int m = 2; m < p - 1; ++m) {
                    if ((p - 1) % m == 0 && IntegerUtils.pow(k, m, p) == 1) {
                        max = m;
                        break;
                    }
                }
                out.println(IntegerUtils.pow(p, (p - 1) / max, MOD));
            }
        }

    }

    static class IntegerUtils {
        public static int pow(int x, int p, int MOD) {
            int result = 1;
            for (int i = p; i > 0; i >>= 1) {
                if ((i & 1) != 0) {
                    result = (int) ((result * 1L * x) % MOD);
                }
                x = (int) ((x * 1L * x) % MOD);
            }
            return result;
        }

    }

    static class InputReader {
        private BufferedReader reader;
        private StringTokenizer stt;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
        }

        public String nextLine() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        public String nextString() {
            while (stt == null || !stt.hasMoreTokens()) {
                stt = new StringTokenizer(nextLine());
            }
            return stt.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(nextString());
        }

    }
}

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

public class CF334B {
	static long N;
	static int MOD = (int) (1e9 + 7);
	static long fac[], ifac[];

	public static void main(String args[]) {
		InputReader in = new InputReader(System.in);
		PrintWriter out = new PrintWriter(System.out);

		int t = 1;
		while (t-- > 0) {
			int n = in.nextInt();
			int k = in.nextInt();
			if (k == 0) {
				System.out.println(mp(n, n - 1));
			} else if (k == 1) {
				System.out.println(mp(n, n));
			} else {
				DisjointSet ds = new DisjointSet(n);
				for (int i = 0; i < n; i++) {
					ds.union((int) ((long) i * (long) k % n) % n, i);
				}
				System.out.println(mp(n, ds.comp - 1));
			}
		}

		out.close();

	}

	static void rand(long a[]) {
		int n = a.length;
		for (int i = 0; i < n; i++) {
			Random r = new Random();
			int j = r.nextInt(n);
			long temp = a[j];
			a[j] = a[i];
			a[i] = temp;
		}

	}

	static long mp(long a, long b) {
		long ans = 1;

		while (b != 0) {
			if (b % 2 == 1)
				ans = (ans * a) % MOD;

			a = (a * a) % MOD;
			b /= 2;

		}
		return ans % MOD;
	}

	static class DisjointSet {
		int[] rank, parent;
		int n;
		int comp;

		DisjointSet(int n) {
			rank = new int[n];
			parent = new int[n];
			this.n = n;
			makeSet();
			comp = n;

		}

		void makeSet() {

			for (int i = 0; i < n; i++) {
				parent[i] = i;
				rank[i] = 1;
			}
		}

		void makeparent(int a) {

			int p = findSet(a);

			if (parent[a] != a) {
				int temp = parent[p];
				parent[a] = a;
				parent[temp] = a;
			}
		}

		int findSet(int x) {
			if (parent[x] != x) {

				parent[x] = findSet(parent[x]);
				rank[x] = rank[parent[x]];
			}

			return parent[x];
		}

		int union(int x, int y) {
			int xRoot = findSet(x);
			int yRoot = findSet(y);
			if (xRoot == yRoot) {
				return rank[xRoot];
			}

			comp--;
			if (rank[xRoot] < rank[yRoot]) {
				parent[xRoot] = yRoot;
				rank[yRoot] += rank[xRoot];

				return rank[yRoot];
			}

			else if (rank[yRoot] < rank[xRoot]) {
				parent[yRoot] = xRoot;
				rank[xRoot] += rank[yRoot];
				return rank[xRoot];
			}

			else {
				parent[yRoot] = xRoot;
				rank[xRoot] = rank[xRoot] * 2;
				return rank[xRoot];
			}
		}

	}

	static class Node implements Comparable<Node> {
		long x;
		long y;

		public Node(long i, long j) {
			x = i;
			y = j;
		}

		public int compareTo(Node p) {
			return Long.compare(this.y, p.y);
		}

	}

	static class InputReader {

		private InputStream stream;
		private byte[] buf = new byte[8192];
		private int curChar;
		private int snumChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream) {
			this.stream = stream;
		}

		public int snext() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int nextInt() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}

			int res = 0;

			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));

			return res * sgn;
		}

		public long nextLong() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = snext();
			}

			long res = 0;

			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));

			return res * sgn;
		}

		public String readString() {
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c) {
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		public interface SpaceCharFilter {
			public boolean isSpaceChar(int ch);
		}
	}
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

/**
*
* Codeforces Round #334 (Div 2) - D: Moodular Arithmetic
*
* In-progress
*
* @author Daniel
*
*/
public class D {

    private static final int M = 1000000007;

    static int expMod(int a, int b) {
        long res = 1;
        for (int i=0; i<b; i++)
            res = (res * a) % M;
        return (int) res;
    }

    static void solve() throws Exception {

        int p = nextInt();
        int k = nextInt();

        //Trivial cases
        if (k == 0)
            System.out.println(expMod(p, p - 1));
        else if (k == 1)
            System.out.println(expMod(p, p));
        else {
            int l = 1;
            for (long n = 1; (n = (n * k) % p) != 1; l++);
            System.out.println(expMod(p, (p - 1)/l));
        }
    }

    /*=============================================================================
     *                          STANDARD I/O TEMPLATE
     * ============================================================================
     */
    static BufferedReader in;
    static BufferedWriter out;
    static StringTokenizer tok;

    public static void main(String[] args) {
        try {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new BufferedWriter(new OutputStreamWriter(System.out));
            solve();
            out.flush();
            out.close();
            in.close();
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    static void print(CharSequence str) throws IOException {
        out.write(str.toString());
    }

    static void println() throws IOException {
        out.write(System.lineSeparator());
    }

    static void println(CharSequence str) throws IOException {
        print(str);
        println();
    }

    static void printf(String format, Object... args) throws IOException {
        print(String.format(format, args));
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    static String next() throws IOException {
        while (tok == null || !tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine());
        }
        return tok.nextToken();
    }

    static String nextLine() throws IOException {
        if (tok == null || !tok.hasMoreTokens())
            return in.readLine();
        else
            return tok.nextToken("\n\r");
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author ilyakor
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        static final long mod = 1000 * 1000 * 1000 + 7;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int p = in.nextInt();
            int k = in.nextInt();
            if (k == 0) {
                long res = IntegerUtils.pow(p, p - 1, mod);
                out.printLine(res);
                return;
            }
            if (k == 1) {
                long res = IntegerUtils.pow(p, p, mod);
                out.printLine(res);
                return;
            }
            int cnt = 0;
            long cur = 1;
            do {
                ++cnt;
                cur = (cur * (long) k) % p;
            } while (cur != 1);
            Assert.assertTrue((p - 1) % cnt == 0);
            long r = (p - 1) / cnt;
            long res = IntegerUtils.pow(p, r, mod);
            out.printLine(res);
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buffer = new byte[10000];
        private int cur;
        private int count;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public static boolean isSpace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int read() {
            if (count == -1) {
                throw new InputMismatchException();
            }
            try {
                if (cur >= count) {
                    cur = 0;
                    count = stream.read(buffer);
                    if (count <= 0)
                        return -1;
                }
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            return buffer[cur++];
        }

        public int readSkipSpace() {
            int c;
            do {
                c = read();
            } while (isSpace(c));
            return c;
        }

        public int nextInt() {
            int sgn = 1;
            int c = readSkipSpace();
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = read();
            } while (!isSpace(c));
            res *= sgn;
            return res;
        }

    }

    static class Assert {
        public static void assertTrue(boolean flag) {
//        if (!flag)
//        while (true);
            if (!flag)
                throw new AssertionError();
        }

    }

    static class IntegerUtils {
        public static long pow(long x, long y, long mod) {
            x %= mod;
            long res = 1;
            while (y > 0) {
                if (y % 2 == 1) {
                    --y;
                    res = BigInteger.valueOf(res).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
                } else {
                    y /= 2;
                    x = BigInteger.valueOf(x).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
                }
            }
            return res % mod;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int p = in.nextInt();
            int k = in.nextInt();
            long ans = 1;
            int mod = (int) 1e9 + 7;
            if (k == 0) {
                for (int i = 0; i < p - 1; i++) {
                    ans = ans * p % mod;
                }
                out.print(ans);
                return;
            }
            if (k == 1) ans = ans * p % mod;
            boolean[] over = new boolean[p];
            for (int i = 1; i < p; i++) {
                if (over[i]) continue;
                ans = ans * p % mod;
                int x = i;
                while (!over[x]) {
                    over[x] = true;
                    x = (int) (1l * x * k % p);
                }
            }
            out.print(ans);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch ( IOException e ) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}

// practice with rainboy
import java.io.*;
import java.util.*;

public class CF603B extends PrintWriter {
	CF603B() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF603B o = new CF603B(); o.main(); o.flush();
	}

	static final int MD = 1000000007;
	long power(int a, int k) {
		return k == 0 ? 1 : power(a, k - 1) * a % MD;
	}
	void main() {
		int p = sc.nextInt();
		int k = sc.nextInt();
		if (k == 0) {
			println(power(p, p - 1));
			return;
		}
		if (k == 1) {
			println(power(p, p));
			return;
		}
		long x = 1;
		int m = 0;
		do {
			x = x * k % p;
			m++;
		} while (x != 1);
		println(power(p, (p - 1) / m));
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        ProblemBMoodularArithmetic solver = new ProblemBMoodularArithmetic();
        solver.solve(1, in, out);
        out.close();
    }

    static class ProblemBMoodularArithmetic {
        int[] parent;
        int mod = (int) 1e9 + 7;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int p = in.readInt();
            long k = in.readInt();
            if (k <= 1) {
                out.println(pow(p, p - 1 + k));
                return;
            }
            parent = new int[p];
            for (int i = 0; i < p; i++) parent[i] = i;
            for (int i = 0; i < p; i++) {
                union(i, (int) ((k * i) % p));
            }
            int cnt = 0;
            for (int i = 1; i < p; i++) if (parent[i] == i) cnt++;
            out.println(pow(p, cnt));
        }

        int find(int v) {
            if (parent[v] == v) return v;
            int p = find(parent[v]);
            return parent[v] = p;
        }

        void union(int a, int b) {
            parent[find(a)] = parent[find(b)];
        }

        long pow(long a, long b) {
            long ans = 1;
            while (b > 0) {
                if (b % 2 == 1) ans *= a;
                ans = ans % mod;
                a = (a * a) % mod;
                b /= 2;
            }
            return ans;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.*;
import java.util.*;

public class R334qBMoodularArithmetic {

	public static void main(String args[]) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter w = new PrintWriter(System.out);

		StringTokenizer st = new StringTokenizer(br.readLine());
		int p = Integer.parseInt(st.nextToken());
		long k = Integer.parseInt(st.nextToken());

		if(k == 0){
			w.println(pow(p , p - 1 , (int)1e9 + 7));
			w.close();
			return;
		}

		if(k == 1){
			w.println(pow(p , p , (int)1e9 + 7));
			w.close();
			return;
		}

		DisjointSet ds = new DisjointSet(p);
		for(int i=0;i<p;i++)
			ds.merge(i, (int)((k * i) % p));

		w.println(pow(p,ds.comp - 1,(int)1e9 + 7));
		w.close();
	}

	public static long pow(int a,int b,int mod){
		if(b == 0)
			return 1;
		long t = pow(a , b / 2, mod);
		t = (t * t) % mod;
		if(b % 2 == 1)
			t = (t * a) % mod;
		return t;
	}

	static public class DisjointSet {

		public int rank[],parent[];
		public int n,comp;

		public DisjointSet(int n){
		    this.n = n;
			makeSet();
		}

		public void makeSet(){
			rank = new int[n];
			parent = new int[n];
			for(int i=0;i<n;i++)
				parent[i] = i;
			comp = n;
		}

		public int find(int x){
			if(parent[x] != x)
				parent[x] = find(parent[x]);
			return parent[x];
		}

		public void merge(int x,int y){
			int xRoot = find(x);
			int yRoot = find(y);

			if(xRoot == yRoot)
				return;

			if(rank[xRoot] < rank[yRoot])
				parent[xRoot] = yRoot;
			else{
				parent[yRoot] = xRoot;
				if(rank[xRoot] == rank[yRoot]){
					parent[yRoot] = xRoot;
					rank[xRoot]++;
				}
			}

			comp--;
		}

	}

}

/**
 * @author nellex
 * Created at: 27-Aug-2016 1:42:14 AM
 */

import java.util.*;

public class CF603B {

	/**
	 * @param args
	 */

	static long p, k;
	static int next[] = new int[1000005];
	static boolean explore[] = new boolean[1000005];

	static void dfs( int x ) {
		if( explore[x] )
			return;
		explore[x] = true;

		dfs( next[x] );
	}

	static long MOD = (long)(1e9)+7;

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner in = new Scanner(System.in);
		p = in.nextInt();
		k = in.nextInt();

		if( k == 0 ) {
			long val = 1;
			for( int i = 0; i < p-1; i++ )
				val = ( val * p )%MOD;
			System.out.println(val);

			return;
		}

		if( k == 1 ) {
			long val = 1;
			for( int i = 0; i < p; i++ )
				val = ( val * p )%MOD;
			System.out.println(val);

			return;
		}

		for( int i = 0; i < p; i++ )
			next[ (int) ((k*i)%p) ] = i;

		Arrays.fill( explore, false );

		long ans = 1;

		for( int i = 0; i < p; i++ ) {
			if( explore[i] || next[i] == i ) continue;
			dfs(i);
			ans = ( ans * p )%MOD;
		}

		System.out.println(ans);
	}

}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class BalabizooFTW
{

	static class DSU
	{
		int rank[];
		int parent[];
		int N;
		int sets;
		int setsize[];

		public DSU(int N)
		{
			this.N = N;
			sets = N;
			parent = new int[N];
			rank = new int[N];
			setsize = new int[N];
			for(int i=0;i<N;i++){ parent[i] = i; setsize[i] = 1; }

		}

		public void union(int x,int y)
		{
			if(isSameSet(x,y)) return;
			sets--;
			int xp = getParent(x);
			int yp = getParent(y);
			if(rank[xp]>rank[yp]){ parent[yp] = xp; setsize[xp]+=setsize[yp];}
			else{
				if(rank[xp]==rank[yp]){
					rank[yp]++;
					parent[xp] = yp;
					setsize[yp]+=setsize[xp];
				}
				else
				{ parent[xp] =yp; setsize[yp] += setsize[xp]; }
			}

		}

		public int getParent(int x){
			if(x==parent[x]) return x;
			return parent[x] = getParent(parent[x]);
		}

		public boolean isSameSet(int x,int y){
			return getParent(x)==getParent(y);
		}

		public int numDisjointSets(){
			return sets;
		}
		public int getSetSize(int x){
			return setsize[getParent(x)];
		}

	}

	static  long  modPow(long a, long b, long m)
	{
		long  tempo;
		if (b ==0 ){
			tempo =  1;  //EXIT condition
		}//if
		else  if (b == 1) tempo = a;
		else { long temp = modPow(a,b/2,m);
		if (b%2 == 0)
			tempo = (temp*temp)%m;
		else
			tempo = ((temp*temp)%m)*a%m;
		}
		return tempo;
	}

	static long p,k;
	public static void main(String[]args)throws Throwable
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer	st = new StringTokenizer(br.readLine());
		p = new Long(st.nextToken());
		k = new Long(st.nextToken());
		if(k == 0)

		{

			System.out.println(modPow(p,p- 1,1000*1000*1000 +7));
			return;

		}
		if(k == 1)
		{
			System.out.println(modPow(p,p,1000*1000*1000 +7));
			return;
		}
		DSU dsu = new DSU((int)p);
		for(int i = 0 ; i < p ; ++i)
		{
			dsu.union(i, (int)((k%p*i%p) % p));
		}

		System.out.println(modPow(p,dsu.numDisjointSets() - 1,1000*1000*1000 +7));

	}

}

import java.io.PrintStream;
import java.util.Scanner;

public class D_Moodular_Arithmetic {
	long pow_mod(long n, long p, long mod) {
		if (p == 1)
			return n % mod;
		long m1 = pow_mod(n, p / 2, mod);
		m1 = m1 * m1;
		m1 %= mod;
		if (p % 2 == 1) {
			m1 *= n;
			m1 %= mod;
		}

		return m1;
	}

	long find_order(long k, long p)
	{
		int order = 1;
		long k_ = k;
		while (k_ != 1)
		{
			k_ *= k;
			k_ %= p;
			order++;
		}

		return order;
	}

	void solve() {
		Scanner in = new Scanner(System.in);
		long p = in.nextInt();
		long k = in.nextInt();
		in.close();

		long res = 0;

		long mod = 1000000000 + 7;

		if (k == 0) {
			res = pow_mod(p, p - 1, mod);
		}

		if (k == 1) {
			res = pow_mod(p, p, mod);
		}

		if (k > 1) {
			long order_k = find_order(k, p);
			long p1ok = (p - 1) / order_k;
			res = pow_mod(p, p1ok, mod);
		}

		// print the result
		PrintStream out = System.out;
		out.println(res);
	}

	/// the main method
	public static void main(String[] args) {
		D_Moodular_Arithmetic o = new D_Moodular_Arithmetic();
		o.solve();
	}
}

/**
 * Created by abhishek on 8/4/2016.
 */
import java.util.*;
import java.io.*;
public class Major {
    static long mod = (long)1E9 + 7;
    static int k;
    static int p;
    static void dfs(int idx,boolean visited[]) {
        visited[idx] = true;
        int a = (int)(idx*1L*k % p);
            if (!visited[a])
                dfs(a,visited);
    }
    static long modpow(long a,long b){
        if(b == 0)return 1;
        long temp = modpow(a,b/2);
        temp = temp*temp % mod;
        if(b % 2 == 1)
            temp = temp*a % mod;
        return temp;
    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        p = Integer.parseInt(st.nextToken());
        k = Integer.parseInt(st.nextToken());
        if(k == 0){
            System.out.println(modpow(p,p - 1));
            return;
        }
        if(k == 1){
            System.out.println(modpow(p,p));
            return;
        }
        boolean visited[] = new boolean[p];
        int cnt = 0;
        for(int i = 1;i < p;i++){
            if(visited[i])continue;
            ++cnt;
            dfs(i,visited);
        }
        System.out.print(modpow(p,cnt));
    }
}

import java.util.*;

public class Main {

	private static final int mod = 1000000007;
	public static long pow(long x, long n, long mod) {
		long res = 1;
		while (n > 0) {
			if((n & 1) == 1)
				res = res * x % mod;
			x = x * x % mod;
			n >>= 1;
		}
		return res;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		long p = in.nextInt(), k = in.nextInt();
		if (k == 0)
			System.out.println(pow(p, p - 1, mod));
		else if (k == 1)
			System.out.println(pow(p, p, mod));
		else {
			long ord = 1;
			long tmp = k;
			while (tmp != 1) {
				tmp = tmp * k % p % mod;
				ord++;
			}
			System.out.println(pow(p, (p - 1) / ord, mod));
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class D {

    public static void main(String[] args) throws Exception {
        new D().run();
        out.close();
    }

    void run() throws Exception {
        final int MOD = 1000000007;
        int p = nextInt();
        long k = nextInt();
        DisjointSets set = new DisjointSets(p);
        for (int i = 0; i < p; ++i) {
            set.union(i, (int) (k * i % p));
        }
        HashSet<Integer> countDiff = new HashSet<>();
        for (int i = 0; i < p; ++i) {
            countDiff.add(set.findRoot(i));
        }
        int deg = countDiff.size();
        if (k == 0) {
            deg = p - 1;
        } else if (k != 1) {
            --deg;
        }
        long res = 1;
        for (int i = 0; i < deg; ++i) {
            res = (res * p) % MOD;
        }
        out.print(res);
    }

    public class DisjointSets {

        public DisjointSets(int nVertexes) {
            root = new int[nVertexes];
            rank = new int[nVertexes];
            for (int i = 0; i < nVertexes; ++i) {
                root[i] = i;
                rank[i] = 1;
            }
        }

        public int findRoot(int x) {
            if (root[x] != x) {
                return root[x] = findRoot(root[x]);
            }
            return x;
        }

        public boolean union(int ind, int[][] e) {
            return union(e[ind]);
        }

        public boolean union(int[] e) {
            return union(e[0], e[1]);
        }

        public boolean union(int x, int y) {
            x = findRoot(x);
            y = findRoot(y);
            if (x != y) {
                if (rank[x] > rank[y]) {
                    root[y] = x;
                } else if (rank[x] < rank[y]) {
                    root[x] = y;
                } else {
                    root[x] = y;
                    ++rank[y];
                }
                return true;
            }
            return false;
        }

        private final int[] root;
        private final int[] rank;
    }

//~~~~~~~~~~~~~~~~~~~~~~~~~~~ template ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    int[] nextIntArray(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; ++i) {
            res[i] = nextInt();
        }
        return res;
    }

    int[][] nextIntArray(int nx, int ny) throws IOException {
        int[][] res = new int[nx][ny];
        for (int i = 0; i < nx; ++i) {
            for (int j = 0; j < ny; ++j) {
                res[i][j] = nextInt();
            }
        }
        return res;
    }

    long[] nextLongArray(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; ++i) {
            res[i] = nextLong();
        }
        return res;
    }

    long[][] nextLongArray(int nx, int ny) throws IOException {
        long[][] res = new long[nx][ny];
        for (int i = 0; i < nx; ++i) {
            for (int j = 0; j < ny; ++j) {
                res[i][j] = nextLong();
            }
        }
        return res;
    }

    void fill(int[][] arr, int val) {
        for (int i = 0; i < arr.length; ++i) {
            Arrays.fill(arr[i], val);
        }
    }

    void fill(int[][][] arr, int val) {
        for (int i = 0; i < arr.length; ++i) {
            fill(arr[i], val);
        }
    }

    int[][] newIntArray(int nx, int ny, int val) {
        int[][] res = new int[nx][ny];
        fill(res, val);
        return res;
    }

    int[][][] newIntArray(int nx, int ny, int nz, int val) {
        int[][][] res = new int[nx][ny][nz];
        fill(res, val);
        return res;
    }

    long[][] newLongArray(int nx, int ny, long val) {
        long[][] res = new long[nx][ny];
        for (int i = 0; i < nx; ++i) {
            Arrays.fill(res[i], val);
        }
        return res;
    }

    long[][][] newLongArray(int nx, int ny, int nz, long val) {
        long[][][] res = new long[nx][ny][nz];
        for (int i = 0; i < nx; ++i) {
            for (int j = 0; j < ny; ++j) {
                Arrays.fill(res[i][j], val);
            }
        }
        return res;
    }

    <T> ArrayList<T>[] newArrayListArray(int sz) {
        ArrayList<T>[] res = new ArrayList[sz];
        for (int i = 0; i < sz; ++i) {
            res[i] = new ArrayList<>();
        }
        return res;
    }

    String nextToken() throws IOException {
        while (strTok == null || !strTok.hasMoreTokens()) {
            String line = in.readLine();
            if (line == null) {
                return null;
            }
            strTok = new StringTokenizer(line);
        }
        return strTok.nextToken();
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }

    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }

    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }

    static StringTokenizer strTok;
    final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    final static PrintWriter out = new PrintWriter(System.out);
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class CF_334_D {
    public static void main(String[] args) throws IOException{
        PrintWriter pw = new PrintWriter(System.out, true);
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

        int k, p;
        String[] line = input.readLine().split(" ");
        p = Integer.parseInt(line[0]);
        k = Integer.parseInt(line[1]);
        int[] P = new int[p];
        boolean[] visited = new boolean[p];
        long cnt = 1, a;

        for(int i = 0; i < p; i++){
            a = (long)i*(long)k;
            a %= p;
            P[i] = (int)a;
        }
        int x;
        for(int i = 1; i < p; i++){
            if(!visited[i]){
                cnt = (cnt*(long)p)%1000000007;
            }
            x = i;
            while(!visited[x]){
                visited[x] = true;
                x = P[x];
            }
        }
        if(k == 1){
            cnt = (cnt*(long)p)%1000000007;
        }
        pw.println(cnt);
        pw.close();
        input.close();
    }
}

import java.io.IOException;
import java.math.BigInteger;
import java.util.InputMismatchException;

public class ModularArithmetic {
    private static final int MOD = 1000000007;
    private static final BigInteger MOD_BI = BigInteger.valueOf(MOD);

    public static void main(String[] args) {
        FasterScanner sc = new FasterScanner();

        int P = sc.nextInt();
        int K = sc.nextInt();

        BigInteger P_BI = BigInteger.valueOf(P);

        if (K == 0) {
            System.out.println(P_BI.modPow(BigInteger.valueOf(P - 1), MOD_BI));
            return;
        } else if (K == 1) {
            System.out.println(P_BI.modPow(P_BI, MOD_BI));
            return;
        }

        int[] T = new int[P];
        boolean[] U = new boolean[P];

        for (long i = 1; i < P; i++) {
            int idx = (int)((i * K) % P);
            T[idx] = (int)i;
        }

        int cnt = 0;
        for (int i = 1; i < P; i++) {
            if (!U[i]) {
                doCycle(T, U, i);
                cnt++;
            }
        }

        System.out.println(P_BI.modPow(BigInteger.valueOf(cnt), MOD_BI));
    }

    public static void doCycle(int[] T, boolean[] U, int idx) {
        while (!U[idx]) {
            U[idx] = true;
            idx = T[idx];
        }
    }

    public static class FasterScanner {
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = System.in.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public String nextString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        private boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
    }
}

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Main {

    static int[] next;
    static boolean[] visit;

    public static void main(String[] args) throws Exception {
        Reader in = new Reader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

        int p, k;
        p = in.nextInt();
        k = in.nextInt();

        next = new int[p];
        visit = new boolean[p];
        Map<Integer, Integer> count = new HashMap<>();
        for (int i = 0; i < p; i++) {
            next[i] = (int) ((((long) k) * ((long) i)) % p);
        }

        int n = dfs(1, 1);

        long mod = 1000000007;

        if (k == 0) n = 1;
        int time = (p - 1) / n;
        long ans = 1;
        for (int i = 0; i < time; i++) {
            ans = (ans * p) % mod;
        }

        if (k == 1) {
            ans = (ans * p) % mod;
        }

        out.println(ans);

        out.flush();
        in.close();
        out.close();
    }

    private static int dfs(int now, int deep) {
        visit[now] = true;
        int x = next[now];
        if (visit[x]) {
            return deep;
        } else {
            return dfs(x, deep + 1);
        }
    }

    static class Reader {
        BufferedReader reader;
        StringTokenizer st;

        Reader(InputStreamReader stream) {
            reader = new BufferedReader(stream);
            st = null;
        }

        void close() throws IOException {
            reader.close();
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        String nextLine() throws IOException {
            return reader.readLine();
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

    }
}

import java.util.Scanner;

public class MoodularArithmetic {
    private static final int MOD = 1000000007;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        int res;

        if (k == 0) {
            res = pow(p, p - 1);
        } else if (k == 1) {
            res = pow(p, p);
        } else {
            int groups = 0;
            boolean[] n = new boolean[p];
            n[0] = true;
            int i = 1;
            while (i < p) {
                if (n[i]) {
                    i++;
                    continue;
                } else {
                    groups++;
                    n[i] = true;
                }

                int j = i;
                while (true) {
                    j = (int) ((1L * j * k) % p);
                    if (n[j]) {
                        break;
                    } else {
                        n[j] = true;
                    }
                }
            }
            res = pow(p, groups);
        }
        System.out.println(res);
    }

    private static int pow(int base, int pow) {
        long res = 1;
        for (int i = 0; i < pow; i++) {
            res = (res * base) % MOD;
        }
        return (int) res;
    }
}

//package codeforces.cfr334div2;

import java.util.Scanner;

/**
 * Created by raggzy on 3/23/2016.
 */
public class D {
    private static final int MOD = 1000000000 + 7;

    private static int mulmod(int a, int b, int mod) {
        return (int) ((((long) a) * b) % mod);
    }

    private static int powmod(int a, int b, int mod) {
        int result = 1;
        for (int i = 0; i < b; i++) {
            result = mulmod(result, a, mod);
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int p = in.nextInt();
        int k = in.nextInt();
        boolean[] fixed = new boolean[p];
        if (k == 0) {
            System.out.println(powmod(p, p - 1, MOD));
        } else {
            int result = k == 1 ? p : 1;
            for (int x = 1; x < p; x++) {
                if (!fixed[x]) {
                    result = mulmod(result, p, MOD);
                    int tmp = x;
                    while (!fixed[tmp]) {
                        fixed[tmp] = true;
                        tmp = mulmod(tmp, k, p);
                    }
                }
            }
            System.out.println(result);
        }
    }
}

import java.util.*;
/*

 */
import java.io.*;
public class d
{
	public static void main(String[] arg)
	{
		new d();
	}
	int p, k;
	long MOD = 1_000_000_007;
	boolean[] used;
	public d()
	{
		FastScanner in = new FastScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		p = in.nextInt();
		k = in.nextInt();
		if(k == 0)
		{
			out.println(pow(p, p-1));
		}
		else if(k == 1)
		{
			out.println(pow(p, p));
		}
		else
		{
			used = new boolean[p];
			long ret = 0;
			for(int i = 0; i < p; i++)
			{
				if(used[i]) continue;
				cycle(i);
				ret++;
			}
			out.println(pow(p, ret-1));
		}
		in.close(); out.close();
	}
	void cycle(int num)
	{
		if(used[num]) return;
		used[num] = true;
		cycle((int)((long)num*k%p));
	}
	long pow(long base, long exp)
	{
		if(exp == 0) return 1;
		if((base&1) == 1) return base * pow(base, exp-1)%MOD;
		else
		{
			long ret = pow(base, exp/2);
			return ret*ret%MOD;
		}
	}
	class FastScanner
	{
		final BufferedReader reader;
		String line;
		int index;
		public FastScanner(InputStream in)
		{
			reader = new BufferedReader(new InputStreamReader(in));
		}
		public FastScanner(File f) throws FileNotFoundException
		{
			reader = new BufferedReader(new FileReader(f));
		}
		public String readLine()
		{
			try
			{
				String line = reader.readLine();
				if(line == null) throw new IOException("End of stream");
				return line;
			}
			catch(IOException exception)
			{
				throw new RuntimeException(exception);
			}
		}
		public String nextLine()
		{
			if(line==null) return readLine();
			String s = line;
			line = null;
			return s.substring(index);
		}
		public String next()
		{
			if(line == null)
			{
				line = readLine();
				index = 0;
			}
			while(index >= line.length())
			{
				line = readLine();
				index = 0;
			}
			while(Character.isWhitespace(line.charAt(index)))
			{
				index++;
				while(index >= line.length())
				{
					line = readLine();
					index = 0;
				}
			}
			int endIndex = index;
			while(endIndex < line.length() && !Character.isWhitespace(line.charAt(endIndex)))
				endIndex++;
			String s = line.substring(index, endIndex);
			index = endIndex;
			return s;
		}
		public int nextInt() { return Integer.parseInt(next()); }
		public long nextLong() { return Long.parseLong(next()); }
		public double nextDouble() { return Double.parseDouble(next()); }
		public void close() {;}
	}
}

import java.math.BigInteger;
import java.util.Scanner;

public class D {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		String[] firstLine = s.nextLine().split(" ");

		boolean[] done = new boolean[Integer.parseInt(firstLine[0])];
		int K = Integer.parseInt(firstLine[1]);

		BigInteger ways = new BigInteger("1");

		if (K != 0 && K != 1) {

		int[] cycles = new int[done.length];

		for (int i = 1; i < done.length; i++) {

			if (!done[i]) {

				done[i] = true;
				int cycleLength = 1;
				long start = (i * (long) K) % done.length;

				while (start != i) {
					if (start < 0 || start > done.length) {

						System.out.println(start);

					}
					done[(int) start] = true;
					start *= K;
					start %= done.length;
					cycleLength++;

				}

				cycles[cycleLength]++;

			}

		}
		long way = 1;
		for (int i = 0; i < cycles.length; i++) {

			if (cycles[i] != 0) {

				for (int j = 0; j < cycles[i]; j++) {

					way *= cycles[i] * i + 1;
					way %= 1000000007;

				}

			}

		}
		System.out.println(way);

		}else if (K == 1) {

			int p = done.length;
			ways = new BigInteger(String.valueOf(p));
			ways = ways.modPow(new BigInteger(String.valueOf(p)), new BigInteger("1000000007"));

			System.out.println(ways);

		}else{

			int p = done.length;
			ways = new BigInteger(String.valueOf(p));
			ways = ways.modPow(new BigInteger(String.valueOf(p - 1)), new BigInteger("1000000007"));

			System.out.println(ways);

		}

		s.close();
		System.exit(0);

	}

}

import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;

public class D {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        long n = scanner.nextLong();
        long k = scanner.nextLong();
        long P = 1000000007;
        long t = 0;
        long tmp = 1;
        if(k==0||k==1) {
           long rez = 1;
           for(int i = 0;i <n-1+k;i++)
               rez = (rez * n)%P;
           System.out.println(rez);
           return;
        }
        while(true) {
            t++;
            tmp = (k*tmp)%n;
            if(tmp==1)break;
        }
        long col = (n-1)/t;
        long rez = 1;
        for(int i = 0;i < col;i++) {
            rez = (rez*n)%P;
        }
        System.out.println(rez);

        scanner.close();
    }

    static StreamTokenizer in;
    static PrintWriter out;

    static int nextInt() throws IOException {
        in.nextToken();
        return ( int ) in.nval;
    }
}

import java.io.*;
import java.util.*;

public class A {

	static int []g;;
	static int []order;
	static int permute(int idx) {
		int ans=0;
		if(idx==order.length) {
			if(simulate()) {
				ans=1;
			}
			return ans;
		}
		for(int i=0;i<order.length;i++) {
			order[idx]=i;
			ans+=permute(idx+1);
		}
		return ans;
	}
	static boolean simulate() {
			for(int i=0;i<order.length;i++) {
				int fg=order[g[i]];
				int gf=g[order[i]];
				if(gf!=fg)
					return false;
			}
			return true;
	}
	static int pow(long b,int e) {
		long ans=1;
		int MOD=(int)1e9+7;
		while(e-->0)
			ans=ans*b%MOD;
		return (int) ans;
	}
	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner();
		PrintWriter out = new PrintWriter(System.out);
		int p=sc.nextInt(),k=sc.nextInt();
		if(k==0) {
			System.out.println(pow(p,p-1));
			return;
		}
		else if(k==1) {
			System.out.println(pow(p,p));
			return;
		}

		int size=0;
		long curr=1;
		while(true) {
			curr=curr*k%p;
			size++;
			if(curr==1)
				break;
		}
		int num=(p-1)/size;
		out.println(pow(p, num));

		out.close();

	}

	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		Scanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		Scanner(String fileName) throws FileNotFoundException {
			br = new BufferedReader(new FileReader(fileName));
		}

		String next() throws IOException {
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		String nextLine() throws IOException {
			return br.readLine();
		}

		int nextInt() throws IOException {
			return Integer.parseInt(next());
		}

		long nextLong() throws NumberFormatException, IOException {
			return Long.parseLong(next());
		}

		double nextDouble() throws NumberFormatException, IOException {
			return Double.parseDouble(next());
		}

		boolean ready() throws IOException {
			return br.ready();
		}

	}

}

import java.util.Scanner;

public class ProblemD {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		int p = input.nextInt();
		int k = input.nextInt();
		if (k == 0){
			System.out.println(computePow(p, p-1));
			System.exit(0);
		}
		if (k == 1){
			System.out.println(computePow(p, p));
			System.exit(0);
		}
		boolean[] hit = new boolean[p];
		hit[0] = true;
		int degrees = 0;
		for(int a = 1; a < p; a++){
			if(hit[a] == false){
				degrees++;
				long temp = a;
				while(hit[(int) temp] == false){
					hit[(int) temp] = true;
					temp = (((long) k) * temp) % ((long) p);
				}
			}
		}
		System.out.println(computePow(p, degrees));
	}

	private static long computePow(int p, int p2) {
		long temp = 1;
		for(int a = 0; a < p2; a++){
			temp = temp * ((long) p);
			temp = temp % ((long) 1000000007);
		}
		return temp;
	}
}

import java.util.Scanner;

public class Main {
	static long mod[];
	public static void build(int k,int p){
		mod = new long[p];
		mod[0] = 1;
		for(int i=1;i<p;i++){
			mod[i] = (mod[i-1]*k)%p;
		}
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		build(k,p);
		boolean[] visited = new boolean[p];
		long answer = 1;
		if(k==0){
			for(int i=1;i<p;i++){
				answer = (answer*p)%1000000007;
			}
		}
		else{
			for(int i=0;i<visited.length;i++){
				if(!visited[i]){
					visited[i] = true;
					int length = 1;
					long x = i;
					long j = (x*k)%p;
					while(j != x){
						length++;
						visited[(int)j] = true;
						j = (k*j)%p;
					}
					if(mod[length] == 1){
						answer = (answer*p)%1000000007;
					}
				}
			}
		}

		System.out.println(answer);
	}
}

import java.io.*;
import java.util.*;

public class CF334D{

    public static long pow(long a, long b) {
        long r = 1;
        for(long i=0; i<b; i++) {
            r = (r*a) % 1000000007;
        }
        return r;
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

        long p = sc.nextInt();
        long k = sc.nextInt();

        long a;

        if (k==0) {
            a = pow(p, p-1);
        } else if (k==1) {
            a = pow(p, p);
        } else {
            long q = k;
            long c = 1;
            while (q != 1) {
                q = (q*k) % p;
                c++;
            }
            a = pow(p, (p-1)/c);
        }

        out.println(a);

        out.close();
    }
}

import java.util.*;

public class D {

    public static void main(String[] args) {
    	Scanner s = new Scanner(System.in);
    	int p, k;
    	p = s.nextInt();
    	k = s.nextInt();
    	if(k == 0) {
    		long ans = 1;
    		for(int i=1; i<p; i++)
    			ans = (ans*p)%1000000007;
    		System.out.println(ans);
    		System.exit(0);
    	}
    	boolean[] graph = new boolean[p];
    	long ans = 1;
    	if(k == 1) ans = p;
    	for(int i=1; i<p; i++) {
    		if(!graph[i]) {
    			long tmp = i;
    			int rot = 0;
    			do {
    				graph[(int)tmp] = true;
    				tmp = (tmp*k)%p;
    				rot++;
    			} while(tmp != i);
    			ans = (ans*p)%1000000007;
    		}
    	}
    	System.out.println(ans);
    }
}

import java.util.*;

public class D334 {
	static long mod;
	public static void main(String[] args) {

		Scanner qwe = new Scanner(System.in);

		long p = qwe.nextLong();
		long k = qwe.nextLong();

		long[] maps = new long[(int)p];
		for (int i = 0; i < maps.length; i++) {
			maps[i] = (i*k)%p;
			//System.out.println("x: " + i + " xp: " + maps[i]);
		}

		HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();

		boolean[] been = new boolean[maps.length];

		for(int i =0; i < maps.length; i++){
			if(!been[i]){
				int size = 1;
				been[i] = true;

				long at = i;
				while(true){
					at = maps[(int)at];
					if(been[(int)at]){
						break;
					}

					been[(int)at] = true;
					size++;

				}
				if(!hm.containsKey(size)) hm.put(size, 0);
				hm.put(size, hm.get(size)+1);

			}
		}

		//System.out.println(hm);

		long ans = 1;
		mod = (int)(1e9+7);

		for(int size : hm.keySet()){
			int amount = hm.get(size);
			long mult = hm.get(size)*size;
			if(size > 1 && hm.containsKey(1)){
				mult += hm.get(1);
			}

			if(size > 2 && size % 2 == 0){
				if(hm.containsKey(2)){
					mult += hm.get(2)*2;
				}
			}

			for(int div = 3; div <= Math.sqrt(size)+1; div += 2){
				if(div == size) break;
				if(size % div ==0 && hm.containsKey(div)){
					mult += hm.get(div)*div;
					mult %= mod;

					int other = size/div;
					if(other > div && hm.containsKey(other)){
						mult += hm.get(other)*other;
						mult %= mod;
					}

				}
			}

			//System.out.println(amount + " " + size + " mult: " + mult);

			mult = fastexpo(mult,amount);
			ans *= mult;
			ans %= mod;
		}

		if(k ==0){
			ans = fastexpo(p,p-1);
		}

		System.out.println(ans);

		qwe.close();
	}

	static long fastexpo(long b, long pow){
		if(pow == 0) return 1l;

		long temp = fastexpo(b,pow/2);
		temp *= temp;
		temp %= mod;
		if(pow % 2 == 1) temp *= b;

		return temp%mod;

	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class D {
	final long MOD = (long)(1e9+7);
	long p,k;
	void readInput() throws NumberFormatException, IOException{
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);
		p = sc.nextLong();
		k = sc.nextLong();
	}

	public static long powmod(long a, long x, long n){
		long res = 1;
		a = a % n;
		while(x>0){
			if ( x % 2 == 1)
				res = (res*a) %n;
			a = (a*a) %n;
			x = x >> 1;
		}
		return res;
	}

	void solve(){
		long ssol = 0;
		if (k==0)
			ssol = powmod(p, p-1, MOD);
		else if (k==1)
			ssol = powmod(p, p, MOD);
		else {
			int ord = 1;
			long q = k;
			while(q!=1)
			{
				q = (q*k) % p;
				if (q<0) q+= p;
				ord++;
			}
			ssol = powmod(p, (p-1)/ord, MOD);
		}
		System.out.println(ssol);
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		D a = new D();
		a.readInput();
		a.solve();
	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author George Marcus
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        private static final long MOD = 1000000007;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int P = in.readInt();
            int K = in.readInt();

            if (K == 0) {
                int ans = fastPow(P, P - 1);
                out.println(ans);
                return;
            }

            long[] pow = new long[P + 1];
            pow[0] = 1;
            for (int i = 1; i <= P; i++) {
                pow[i] = pow[i - 1] * K % P;
            }

            int[] to = new int[P];
            for (int x = 0; x < P; x++) {
                int y = (int) ((long) x * K % P);
                to[x] = y;
            }

            int[] v = new int[P];
            int cnt = 0;
            for (int i = 0; i < P; i++) {
                int idx = i + 1;
                int x = i;
                if (v[x] != 0 && v[x] != idx) {
                    continue;
                }
                int start = -1;
                while (true) {
                    v[x] = idx;
                    int y = to[x];
                    if (v[y] != 0) {
                        if (v[y] == idx) {
                            start = y;
                        }
                        break;
                    }
                    x = y;
                }
                if (start == -1) {
                    continue;
                }

                int len = 1;
                x = start;
                while (to[x] != start) {
                    x = to[x];
                    len++;
                }

                long kpow = pow[len];
                if (kpow == 1) {
                    cnt++;
                }
            }

            int ans = fastPow(P, cnt);
            out.println(ans);
        }

        private int fastPow(long a, int p) {
            long ret = 1;
            while (p > 0) {
                if ((p & 1) > 0) {
                    ret = ret * a % MOD;
                }
                a = a * a % MOD;
                p >>= 1;
            }
            return (int) ret;

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.util.*;
public class moodular {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		long p=sc.nextLong();
		long k=sc.nextLong();
		long t;
		if (k==0) t=p-1;
		else if (k==1) t=p;
		else t=(p-1)/order(k,p);
		long ans=1;
		for (long i=0; i<t; i++) {
			ans=(ans*p)%(1000000007);
		}
		System.out.println(ans);
	}

	public static long order(long k, long p) {
		long n=1;
		long temp=k;
		while (true) {
			if (temp==1) return n;
			else {
				n++;
				temp=(temp*k)%p;
			}
		}
	}

}

//package round334;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class B {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int mod = 1000000007;
		int p = ni(), K = ni();
		if(K == 0){
			out.println(pow(p, p-1, mod));
		}else{
			DJSet ds = new DJSet(p);
			for(int i = 1;i < p;i++){
				ds.union(i, (int)((long)i*K%p));
			}
			out.println(pow(p, ds.count()-1, mod));
		}
	}

	public static class DJSet {
		public int[] upper;

		public DJSet(int n) {
			upper = new int[n];
			Arrays.fill(upper, -1);
		}

		public int root(int x) {
			return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
		}

		public boolean equiv(int x, int y) {
			return root(x) == root(y);
		}

		public boolean union(int x, int y) {
			x = root(x);
			y = root(y);
			if (x != y) {
				if (upper[y] < upper[x]) {
					int d = x;
					x = y;
					y = d;
				}
				upper[x] += upper[y];
				upper[y] = x;
			}
			return x == y;
		}

		public int count() {
			int ct = 0;
			for (int u : upper)
				if (u < 0)
					ct++;
			return ct;
		}
	}

	public static long pow(long a, long n, long mod) {
		//		a %= mod;
		long ret = 1;
		int x = 63 - Long.numberOfLeadingZeros(n);
		for (; x >= 0; x--) {
			ret = ret * ret % mod;
			if (n << 63 - x < 0)
				ret = ret * a % mod;
		}
		return ret;
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new B().run(); }

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

import java.io.*;

public class Main {
    final static double mod = 1e9 + 7;
	public static void main (String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input = bf.readLine().split(" ");
		long p = Long.parseLong(input[0]);
		long k = Long.parseLong(input[1]);
		long order = 1;
		long temp = k;

		if (k == 0)
		    System.out.println((int)Math.pow(p, p - 1));
		else {
    	    while (temp != 1) {
    	        temp = (k * temp) % p;
    	        order++;
    	    }

    	    if (k == 1)
		        System.out.println(((Math.pow(p,p) % (int) mod)));
		    else
		        System.out.println((((int)Math.pow(p, (p - 1)/order)) % (int) mod));
		}
	}
}

import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;

public class D {

    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        long n = scanner.nextLong();
        long k = scanner.nextLong();
        long P = 1000000007;
        long t = 0;
        long tmp = 1;
        if(k==0) {
           long rez = 1;
           for(int i = 0;i <n-1;i++)
               rez = (rez * n)%P;
           System.out.println(rez);
           return;
        }
        while(true) {
            t++;
            tmp = (k*tmp)%n;
            if(tmp==1)break;
        }
        long col = (n-1)/t;
        long rez = 1;
        for(int i = 0;i < col;i++) {
            rez = (rez*n)%P;
        }
        System.out.println(rez);

        scanner.close();
    }

    static StreamTokenizer in;
    static PrintWriter out;

    static int nextInt() throws IOException {
        in.nextToken();
        return ( int ) in.nval;
    }
}

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class Round334B {

	public static final int mod = (int)1e9+7;
	public static LinkedList<Integer>[] adj;

	public static boolean[] visited;

	public static void dfs(int curr) {
		visited[curr] = true;
		for(Integer x : adj[curr]) {
			if(!visited[x]) {
				dfs(x);
			}
		}
	}

	public static int components() {
		int n = adj.length;
		int ans = 0;
		visited = new boolean[n];
		for(int i = 1; i < n; i++) {
			if(!visited[i]) {
				dfs(i);
				ans++;
			}
		}
		return ans;
	}

	public static void solve() {
		int p = s.nextInt();
		int k = s.nextInt();
		adj = new LinkedList[p];
		for(int i = 0; i < p; i++) {
			adj[i] = new LinkedList<Integer>();
		}
		for(int i = 1; i < p; i++) {
			long val = (long)k * (long)i;
			val %= p;
			adj[(int)val].add(i);
		}
		int pow = components();
		if(k == 1 || k == 0) {
			pow++;
		}
		long ans = fast(p, pow);
		out.println(ans);
	}

	public static long fast(long a, int n) {
		if(n == 1) {
			return a;
		}
		long ans = fast(a, n/2);
		ans = ans * ans;
		ans %= mod;
		if(n % 2 == 1) {
			ans = ans * a;
			ans %= mod;
		}
		return ans;
	}

	public static void main(String[] args) {
		out = new PrintWriter(new BufferedOutputStream(System.out));
		s = new FastReader();
		solve();
		out.close();
	}

	public static FastReader s;
	public static PrintWriter out;

	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return str;
		}
	}

}

//package codeforces.cfr334div2;

import java.util.Scanner;

/**
 * Created by raggzy on 3/23/2016.
 */
public class D {
    private static int mulmod(int a, int b) {
        return (int) ((((long) a) * b) % 1000000007);
    }

    private static int powmod(int a, int b) {
        int result = 1;
        for (int i = 0; i < b; i++) {
            result = mulmod(result, a);
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int p = in.nextInt();
        int k = in.nextInt();
        boolean[] fixed = new boolean[p];
        if (k == 0) {
            System.out.println(powmod(p, p - 1));
        } else {
            int result = 1;
            for (int x = 1; x < p; x++) {
                if (!fixed[x]) {
                    result = mulmod(result, p);
                    int tmp = x;
                    while (!fixed[tmp]) {
                        fixed[tmp] = true;
                        tmp = (tmp * k) % p;
                    }
                }
            }
            System.out.println(result);
        }
    }
}

import java.util.*;

public class MoodularArithmetic {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		if (k == 0) {
			long ans = 1;
			for (int i = 0; i < p - 1; i++) {
				ans *= p;
			}
			System.out.println(ans);
		}
		else {
			long a = k;
			int ord = 1;
			while (a != 1) {
				a *= k;
				a %= p;
				ord++;
			}
			long ans = 1;
			for (int i = 0; i < (p - 1) / ord; i++) {
				ans *= p;
				ans %= 1000000007;
			}
			System.out.println(ans);
		}
		sc.close();
		System.exit(0);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        ProblemBMoodularArithmetic solver = new ProblemBMoodularArithmetic();
        solver.solve(1, in, out);
        out.close();
    }

    static class ProblemBMoodularArithmetic {
        int[] parent;
        int mod = (int) 1e9 + 7;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int p = in.readInt();
            long k = in.readInt();
            if (k == 0) {
                out.println(pow(p, p - 1));
                return;
            }
            parent = new int[p];
            for (int i = 0; i < p; i++) parent[i] = i;
            for (int i = 0; i < p; i++) {
                union(i, (int) ((k * i) % p));
            }
            int cnt = 0;
            for (int i = 1; i < p; i++) if (parent[i] == i) cnt++;
            out.println(pow(p, cnt));
        }

        int find(int v) {
            if (parent[v] == v) return v;
            int p = find(parent[v]);
            return parent[v] = p;
        }

        void union(int a, int b) {
            parent[find(a)] = parent[find(b)];
        }

        long pow(long a, long b) {
            long ans = 1;
            while (b > 0) {
                if (b % 2 == 1) ans *= a;
                ans = ans % mod;
                a = (a * a) % mod;
                b /= 2;
            }
            return ans;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author George Marcus
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        private static final long MOD = 1000000007;
        int[] v;
        int[] to;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int P = in.readInt();
            int K = in.readInt();

            to = new int[P];

            long[] pow = new long[P + 1];
            pow[0] = 1;
            for (int i = 1; i <= P; i++) {
                pow[i] = pow[i - 1] * K % P;
            }

            for (int x = 0; x < P; x++) {
                int y = (int) ((long) x * K % P);
                to[x] = y;
            }

            v = new int[P];

            int cnt = 0;
            for (int i = 0; i < P; i++) {
                int idx = i + 1;
                int x = i;
                if (v[x] != 0 && v[x] != idx) {
                    continue;
                }
                int start = -1;
                while (true) {
                    v[x] = idx;
                    int y = to[x];
                    if (v[y] != 0) {
                        if (v[y] == idx) {
                            start = y;
                        }
                        break;
                    }
                    x = y;
                }
                if (start == -1) {
                    continue;
                }

                int len = 1;
                x = start;
                while (to[x] != start) {
                    x = to[x];
                    len++;
                }

                long kpow = pow[len];
                if (kpow == 1) {
                    cnt++;
                }
            }

            int ans = fastPow(P, cnt);
            out.println(ans);
        }

        private int fastPow(long a, int p) {
            long ret = 1;
            while (p > 0) {
                if ((p & 1) > 0) {
                    ret = ret * a % MOD;
                }
                a = a * a % MOD;
                p >>= 1;
            }
            return (int) ret;

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author xwchen
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public static int cnt;
        public static int N = 1000002;
        public static Edge[] edges = new Edge[1000000 * 2 + 5];
        public static int[] head = new int[N];
        public static boolean[] vis = new boolean[N];

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            long p = in.nextLong();
            long k = in.nextLong();
            long mod = 1000000007;

            Arrays.fill(head, -1);
            Arrays.fill(vis, false);
            for (int i = 0; i < N * 2; ++i) {
                edges[i] = new Edge();
            }
            cnt = 0;
            long ret = 1;
            for (int i = 1; i < p; ++i) {
                addEdge((int) (k * i % p), i);
                addEdge(i, (int) (k * i % p));
            }
            if (k == 0) {
                for (int i = 1; i < p; ++i) {
                    ret = ret * p % mod;
                }
                out.println(ret);
                return;
            }
            int count = 0;
            for (int i = 1; i < p; ++i) {
                if (!vis[i]) {
                    dfs(i, i);
                    ++count;
                }
            }
            //out.println("p="+p+" cnt = "+count);
            for (int i = 0; i < count; ++i) {
                ret = ret * p % mod;
            }
            out.println(ret);
        }

        public static void dfs(int u, int pre) {
            vis[u] = true;
            for (int e = head[u]; e != -1; e = edges[e].pre) {
                int v = edges[e].v;
                if (!vis[v]) {
                    dfs(v, u);
                }
            }
        }

        public static void addEdge(int u, int v) {
            edges[cnt].u = u;
            edges[cnt].v = v;
            edges[cnt].pre = head[u];
            head[u] = cnt++;
        }

        class Edge {
            int u;
            int v;
            int pre;

        }

    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static MyScanner   in;
    static PrintWriter out;
//    static Timer timer = new Timer();

    public static void main(String[] args) throws IOException {
        in = new MyScanner();
        out = new PrintWriter(System.out, true);

        int n = in.nextInt();
        int k = in.nextInt();

        int cycles = 0;
        boolean[] was = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (!was[i]) {
                paint(i, n, k, was);
                cycles++;
            }
        }

        out.println(pow(n, cycles - 1, (long) 1e9 + 7));
    }

    private static long pow(long x, int n, long MOD) {
        if (n == 0) return 1;
        if (n % 2 == 1) {
            return (x * pow(x, n - 1, MOD)) % MOD;
        } else {
            return pow((x * x) % MOD, n / 2, MOD);
        }
    }

    private static void paint(int i, int p, int k, boolean[] was) {
        if (was[i]) return;
        was[i] = true;
        paint((int) (((long) i * k) % p), p, k, was);
    }
}
class MyScanner {

    public static final String CP1251 = "cp1251";

    private final BufferedReader  br;
    private       StringTokenizer st;
    private       String          last;

    public MyScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public MyScanner(String path) throws IOException {
        br = new BufferedReader(new FileReader(path));
    }

    public MyScanner(String path, String decoder) throws IOException {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder));
    }

    String next() throws IOException {
        while (st == null || !st.hasMoreElements())
            st = new StringTokenizer(br.readLine());
        last = null;
        return st.nextToken();
    }

    String next(String delim) throws IOException {
        while (st == null || !st.hasMoreElements())
            st = new StringTokenizer(br.readLine());
        last = null;
        return st.nextToken(delim);
    }

    String nextLine() throws IOException {
        st = null;
        return (last == null) ? br.readLine() : last;
    }

    boolean hasNext() {
        if (st != null && st.hasMoreElements())
            return true;

        try {
            while (st == null || !st.hasMoreElements()) {
                last = br.readLine();
                st = new StringTokenizer(last);
            }
        }
        catch (Exception e) {
            return false;
        }

        return true;
    }

    String[] nextStrings(int n) throws IOException {
        String[] arr = new String[n];
        for (int i = 0; i < n; i++)
            arr[i] = next();
        return arr;
    }

    String[] nextLines(int n) throws IOException {
        String[] arr = new String[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextLine();
        return arr;
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    int[] nextInts(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextInt();
        return arr;
    }

    Integer[] nextIntegers(int n) throws IOException {
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextInt();
        return arr;
    }

    int[][] next2Ints(int n, int m) throws IOException {
        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextInt();
        return arr;
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    long[] nextLongs(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextLong();
        return arr;
    }

    long[][] next2Longs(int n, int m) throws IOException {
        long[][] arr = new long[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextLong();
        return arr;
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(next().replace(',', '.'));
    }

    double[] nextDoubles(int size) throws IOException {
        double[] arr = new double[size];
        for (int i = 0; i < size; i++)
            arr[i] = nextDouble();
        return arr;
    }

    double[][] next2Doubles(int n, int m) throws IOException {
        double[][] arr = new double[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextDouble();
        return arr;
    }

    boolean nextBool() throws IOException {
        String s = next();
        if (s.equalsIgnoreCase("true") || s.equals("1"))
            return true;

        if (s.equalsIgnoreCase("false") || s.equals("0"))
            return false;

        throw new IOException("Boolean expected, String found!");
    }
}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 * @author pttrung
 */
public class B_Round_334_Div1 {

    public static long MOD = 1000000007;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int p = in.nextInt();
        int k = in.nextInt();
        long[]l = new long[p + 1];
        int[]check = new int[p];
        check[0] = 1;
        l[1]++;
        for(int i = 1; i < p; i++){
        	if(check[i] == 0){
        		int v = i;
        		int c = 0;
        		do{
        			check[v] = -1;
        			c++;
        			v = (k*v) % p;
        		}while(check[v] == 0);
        		check[i] = c;
        		l[c]++;
        	}
        }
        //System.out.println(Arrays.toString(l) + " " + Arrays.toString(check));
        long[]pre = new long[p + 1];
        pre[0] = 1;
        for(int i = 1; i < pre.length; i++){
        	pre[i] = (long)i * pre[i -1];
        	pre[i] %= MOD;
        }
        long result = 1;
        for(int i = 0 ; i < p; i++){
        	if(check[i] != -1){
        		long total = 0;
        		for(int j = 1; j* j <= check[i]; j++){
        		    if(check[i] % j == 0){
        		    	int  o = check[i] / j;
        		    	total += (l[j]*pre[j]) % MOD;
        		    	total %= MOD;
        		    	if(o != j){
        		    		total += (l[o]*pre[o]) % MOD;
            		    	total %= MOD;
        		    	}
        		    }
        		}
        		//System.out.println(total + " " + i);
        		result *= total;
        	}
        }
        out.println(result);
        out.close();
    }

    public static int[] KMP(String val) {
        int i = 0;
        int j = -1;
        int[] result = new int[val.length() + 1];
        result[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(j) != val.charAt(i)) {
                j = result[j];
            }
            j++;
            i++;
            result[i] = j;
        }
        return result;

    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    public static int digit(long n) {
        int result = 0;
        while (n > 0) {
            n /= 10;
            result++;
        }
        return result;
    }

    public static double dist(long a, long b, long x, long y) {
        double val = (b - a) * (b - a) + (x - y) * (x - y);
        val = Math.sqrt(val);
        double other = x * x + a * a;
        other = Math.sqrt(other);
        return val + other;

    }

    public static class Point implements Comparable<Point> {

        int x, y;

        public Point(int start, int end) {
            this.x = start;
            this.y = end;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 47 * hash + this.x;
            hash = 47 * hash + this.y;
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Point other = (Point) obj;
            if (this.x != other.x) {
                return false;
            }
            if (this.y != other.y) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Point o) {
            return x - o.x;
        }
    }

    public static class FT {

        long[] data;

        FT(int n) {
            data = new long[n];
        }

        public void update(int index, long value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public long get(int index) {
            long result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

    public static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static long pow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }
        long val = pow(a, b / 2);
        if (b % 2 == 0) {
            return val * val % MOD;
        } else {
            return val * (val * a % MOD) % MOD;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            //  br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
        }

        public String next() {

            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

import java.io.*;
import java.util.*;
public class B603 {
public static void main(String[] args) throws IOException {
    input.init(System.in);
    PrintWriter out = new PrintWriter(System.out);
    int p = input.nextInt(), k = input.nextInt();
    boolean[] used = new boolean[p];
    used[0] = true;
    int cyc = 1;
    for(int i = 1; i<p; i++)
    {
        if(used[i]) continue;
        int at = i;
        while(true)
        {
            if(used[at]) break;
            used[at] = true;
            at = (int) ((long)at*k);
            at %= p;
        }
        cyc++;
    }
    if(k == 0)
    {
        out.println(pow(p,p-1));
    }
    else if(p == 1)
    {
        out.println(pow(p, cyc));
    }
    else
    {
        out.println(pow(p, cyc-1));
    }
    out.close();
}
static long pow(long n, long p)
{
    if(p == 0) return 1;
    if(p%2 == 0)
    {
        long sqrt = pow(n,p>>1);
        return (sqrt*sqrt)%1000000007;
    }
    return (n * pow(n,p-1))%1000000007;
}
public static class input {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    static void init(InputStream input) {
    reader = new BufferedReader(new InputStreamReader(input));
    tokenizer = new StringTokenizer("");
    }

    static String next() throws IOException {
    while (!tokenizer.hasMoreTokens())
        tokenizer = new StringTokenizer(reader.readLine());
    return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
    return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {
    return Double.parseDouble(next());
    }

    static long nextLong() throws IOException {
    return Long.parseLong(next());
    }
}
}

import java.util.HashMap;
import java.util.Scanner;

public class D {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		String[] firstLine = s.nextLine().split(" ");

		boolean[] done = new boolean[Integer.parseInt(firstLine[0])];
		int K = Integer.parseInt(firstLine[1]);

		long ways = 1;

		int[] cycles = new int[done.length];

		for (int i = 1; i < done.length; i++) {

			if (!done[i]) {

				done[i] = true;
				int cycleLength = 1;
				int start = (i * K) % done.length;

				while (start != i) {

					done[start] = true;
					start *= K;
					start %= done.length;
					cycleLength++;

				}

				cycles[cycleLength]++;

			}

		}

		for (int i = 0; i < cycles.length; i++) {

			if (cycles[i] != 0) {

				for (int j = 0; j < cycles[i]; j++) {

					ways *= 2 * cycles[i] + 1;
					ways %= 1000000007;

				}

			}

		}

		System.out.println(ways);

		s.close();
		System.exit(0);

	}

}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Div2_334_D
{
	static final int MOD = 1000000007;
	static int [] comp;
	public static long pow(int b, int exp) {
		long res = b;
		while(exp != 1) {
			res = ((res%MOD)*(res%MOD))%MOD;
			if(exp%2 == 1)
				res = (res*b)%MOD;
			exp /= 2;
		}
		return res;
	}
	public static int dfs(int i, int p, int k, int num) {
		int next = (int) ((1l*k*i)%p);
		//System.out.println(i+" "+next);
		if(comp[next] == -1) {
			comp[next] = num;
			comp[next] = Math.min(comp[next], dfs(next, p, k, num));
		}
		return comp[next];
	}
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		if(k == 0)
			System.out.println(pow(p, p-1));
		else if(k == 1)
			System.out.println(pow(p, p));
		else {
			comp = new int[p];
			for(int i = 1;i < p;i++)
				comp[i] = -1;
			int num = 0;
			for(int i = 1;i < p;i++) {
				if(comp[i] == -1) {
					comp[i] = num+1;
					int ret = dfs(i, p, k, num+1);
					comp[i] = Math.min(comp[i], ret);
					//System.out.println(ret);
					if(ret > num) {
						//System.out.println(i+" "+num+" "+ret);
						num++;
					}
				}
			}
			System.out.println(pow(p, num));
		}
	}
}

import java.io.*;
import java.util.*;

public class B {
	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/T";

	FastScanner in;
	PrintWriter out;

	final int MOD = 1000000007;
	int loopSize;
	boolean[] vis;
	ArrayList<Integer>[] g;

	void dfs(int start, int u, int dep) {
		if (start == u && dep != 0) {
			loopSize = dep;
			return;
		}
		for (int v : g[u]) {
			dfs(start, v, dep + 1);
		}
		if (loopSize != -1) {
			vis[u] = true;
		}
	}

	public void solve() {
		int p = in.nextInt(), k = in.nextInt();

		int now = 0;
		int selfLoop = 0;
		for (int i = 0; i < p; i++) {
			if (now == i) selfLoop++;
			now = (now + k) % p;
		}

		g = new ArrayList[p];
		for (int i = 0; i < p; i++)
			g[i] = new ArrayList<Integer>();

		long res = 1;
		vis = new boolean[p];
		for (long i = 0; i < p; i++) {
			int from = (int)((i * k) % p);
			g[from].add((int)i);
		}

		for (int from = 0; from < p; from++) {
			if (vis[from]) continue;

			loopSize = -1;
			dfs(from, from, 0);

			if (loopSize == 1) {
				res = (res * selfLoop) % MOD;
			} else if (loopSize != -1) {
				res = (res * p) % MOD;
			}
		}
		System.out.println(res);
	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		solve();
	}

	public static void main(String[] args) {
		new B().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import java.io.*;
import java.util.*;

public class B {
	InputStream is;

	int __t__ = 1;
	int __f__ = 0;
	int __FILE_DEBUG_FLAG__ = __f__;
	String __DEBUG_FILE_NAME__ = "src/T";

	FastScanner in;
	PrintWriter out;

	final int MOD = 1000000007;
	int loopSize;
	boolean[] vis;
	ArrayList<Integer>[] g;

	void dfs(int start, int u, int dep) {
		if (start == u && dep != 0) {
			loopSize = dep;
			return;
		}
		vis[u] = true;
		dfs(start, g[u].get(0), dep + 1);
	}

	public void solve() {
		int p = in.nextInt(), k = in.nextInt();
		if (k == 0) {
			System.out.println(1);
			return;
		}
		int now = 0;
		int selfLoop = 0;
		for (int i = 0; i < p; i++) {
			if (now == i) selfLoop++;
			now = (now + k) % p;
		}

		g = new ArrayList[p];
		for (int i = 0; i < p; i++)
			g[i] = new ArrayList<Integer>();

		long res = 1;
		vis = new boolean[p];
		for (long i = 0; i < p; i++) {
			int from = (int)((i * k) % p);
			g[from].add((int)i);
		}

		for (int from = 0; from < p; from++) {
			if (vis[from]) continue;

			loopSize = -1;
			dfs(from, from, 0);

			if (loopSize == 1) {
				res = (res * selfLoop) % MOD;
			} else {
				res = (res * p) % MOD;
			}
		}
		System.out.println(res);
	}

	public void run() {
		if (__FILE_DEBUG_FLAG__ == __t__) {
			try {
				is = new FileInputStream(__DEBUG_FILE_NAME__);
			} catch (FileNotFoundException e) {
				// TODO 自動生成された catch ブロック
				e.printStackTrace();
			}
			System.out.println("FILE_INPUT!");
		} else {
			is = System.in;
		}
		in = new FastScanner(is);
		out = new PrintWriter(System.out);

		solve();
	}

	public static void main(String[] args) {
		new B().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import java.util.*;

public class Modular {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        long p = scan.nextInt();
        long k = scan.nextInt();

        if(k > 1 && (k < p - 1)) {
            System.out.println(1);
            return;
        }

        long half = (p - 1) / 2;
        long res = 1;
        long mod = (long)Math.pow(10, 9) + 7;

        for(long i = 1; i <= half; i++) {
            res = (res * p) % mod;
        }

        if(k == p - 1) {
            System.out.println(res);
            return;
        }

        for(long i = half+1; i <= p-1; i++) {
            res = (res * p) % mod;
        }

        if(k == 0) {
            System.out.println(res);
            return;
        }

        res = (res * p) % mod;
        System.out.println(res);
    }
}

import java.util.*;
import java.io.*;

public class B {
    FastScanner in;
    PrintWriter out;
    boolean[] used;
    long[] pow;
    static long p, k;
    final long MOD = (long) 1e9 + 7;

    public void dfs(long v) {
        used[(int) v] = true;
        if (!used[(int) ((k * v) % p)]) {
            dfs((k * v) % p);
        }
    }

    public void solve() throws IOException {
        p = in.nextInt();
        k = in.nextInt();
        used = new boolean[(int) p];
        pow = new long[(int) p + 1];
        pow[0] = 1;
        for (int i = 0; i < p; i++) {
            pow[i + 1] = (pow[i] * p) % MOD;
        }
        int ans = 0;
        for (int i = 1; i < p; i++) {
            if (!used[i]) {
                dfs(i);
                ans++;
            }
        }
        out.println(pow[((int) p - 1) / 2]);
    }

    public void run() {
        try {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
            solve();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }

    public static void main(String[] arg) {
        new B().run();
    }
}

import java.io.*;
import java.lang.Math;
import java.util.*;

public class Main
{
	public BufferedReader in;
	public PrintStream out;

	public boolean log_enabled = true;

	public long M = 1000000007;

	public void test()
	{
		long p = readInt();
		long k = readInt();

		long x = k;
		long c = 1;

		if (k==0)
		{
			k = p-1;
		}
		else
		{
			while (x!=1)
			{
				c ++;
				x = (k*x) % p;
			}

			k = (p-1) / c;
		}

		x = 1;
		long d = 1;
		while (2*d <= k) d *= 2;

		while (d>0)
		{
			x = (x * x) % M;
			if ((k & d) > 0)
			{
				x = (x * p) % M;
			}

			d = d >> 1;
		}

		out.println(x);
	}

	public void run()
	{
		try
		{
			in = new BufferedReader(new InputStreamReader(System.in));
			out = System.out;

			//in = new BufferedReader(new FileReader("in.txt"));
			//out = new PrintStream(new File("out.txt"));

		}
		catch (Exception e)
		{
			return;
		}

		//while (true)
		{
			//int t = readInt(); for (int i=0; i<t; i++)
			{
				test();
			}
		}
	}

	public static void main(String args[])
	{
		new Main().run();
	}

	private StringTokenizer tokenizer = null;

	public int readInt()
	{
        return Integer.parseInt(readToken());
    }

    public long readLong()
	{
        return Long.parseLong(readToken());
    }

    public double readDouble()
	{
        return Double.parseDouble(readToken());
    }

	public String readLn()
	{
		try
		{
			String s;
			while ((s = in.readLine()).length()==0);
			return s;
		}
		catch (Exception e)
		{
			return "";
		}
	}

    public String readToken()
	{
		try
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				tokenizer = new StringTokenizer(in.readLine());
			}
			return tokenizer.nextToken();
		}
		catch (Exception e)
		{
			return "";
		}
    }

	public int[] readIntArray(int n)
	{
		int[] x = new int[n];
		readIntArray(x, n);
		return x;
	}

	public void readIntArray(int[] x, int n)
	{
		for (int i=0; i<n; i++)
		{
			x[i] = readInt();
		}
	}

	public void logWrite(String format, Object... args)
	{
		if (!log_enabled)
		{
			return;
		}

		out.printf(format, args);
	}
}

import java.io.*;
import java.lang.Math;
import java.util.*;

public class Main
{
	public BufferedReader in;
	public PrintStream out;

	public boolean log_enabled = true;

	public long M = 1000000007;

	public void test()
	{
		long p = readInt();
		long k = readInt();

		if (k==0)
		{
			out.println(1);
			return;
		}

		long x = k;
		long c = 1;
		while (x!=1)
		{
			c ++;
			x = (k*x) % p;
		}

		k = (p-1) / c;

		x = 1;
		long d = 1;
		while (2*d <= k) d *= 2;

		while (d>0)
		{
			x = (x * x) % M;
			if ((k & d) > 0)
			{
				x = (x * p) % M;
			}

			d = d >> 1;
		}

		out.println(x);
	}

	public void run()
	{
		try
		{
			in = new BufferedReader(new InputStreamReader(System.in));
			out = System.out;

			//in = new BufferedReader(new FileReader("in.txt"));
			//out = new PrintStream(new File("out.txt"));

		}
		catch (Exception e)
		{
			return;
		}

		//while (true)
		{
			//int t = readInt(); for (int i=0; i<t; i++)
			{
				test();
			}
		}
	}

	public static void main(String args[])
	{
		new Main().run();
	}

	private StringTokenizer tokenizer = null;

	public int readInt()
	{
        return Integer.parseInt(readToken());
    }

    public long readLong()
	{
        return Long.parseLong(readToken());
    }

    public double readDouble()
	{
        return Double.parseDouble(readToken());
    }

	public String readLn()
	{
		try
		{
			String s;
			while ((s = in.readLine()).length()==0);
			return s;
		}
		catch (Exception e)
		{
			return "";
		}
	}

    public String readToken()
	{
		try
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				tokenizer = new StringTokenizer(in.readLine());
			}
			return tokenizer.nextToken();
		}
		catch (Exception e)
		{
			return "";
		}
    }

	public int[] readIntArray(int n)
	{
		int[] x = new int[n];
		readIntArray(x, n);
		return x;
	}

	public void readIntArray(int[] x, int n)
	{
		for (int i=0; i<n; i++)
		{
			x[i] = readInt();
		}
	}

	public void logWrite(String format, Object... args)
	{
		if (!log_enabled)
		{
			return;
		}

		out.printf(format, args);
	}
}

import java.util.Scanner;

public class Main {
	static int mod[];
	public static void build(int k,int p){
		mod = new int[p];
		mod[0] = 1;
		for(int i=1;i<p;i++){
			mod[i] = (mod[i-1]*k)%p;
		}
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		build(k,p);
		boolean[] visited = new boolean[p];
		long answer = 1;
		if(k==0){
			for(int i=1;i<p;i++){
				answer = (answer*p)%1000000007;
			}
		}
		else{
			for(int i=1;i<visited.length;i++){
				if(!visited[i]){
					visited[i] = true;
					int length = 1;
					int j = (k*i)%p;
					while(j != i){
						length++;
						visited[j] = true;
						j = (k*j)%p;
					}
					if(mod[length] == 1){
						answer = (answer*p)%1000000007;
					}
				}
			}
		}

		System.out.println(answer);
	}
}

import java.util.*;
public class b {
    public static long mod = 1000000007;
    public static void main(String[] args){
        Scanner br = new Scanner(System.in);
        int p = br.nextInt();
        long k = br.nextInt();

        int[] out = new int[p];
        for(int i = 0;i<p;i++){
            out[(int)((i*k)%p)] = i;
        }

        if(k == 0){
            System.out.println(pow(p, p-1, mod));
        }
        else{

            int cycles = 0;
            boolean[] done = new boolean[p];
            for(int i = 0;i<p;i++){
                if(!done[i]){
                    cycles++;
                    int cur = i;
                    while(!done[cur]){

                        done[cur] = true;
                        cur = out[cur];
                    }
                }
            }
            System.out.println(pow(p, cycles-1, mod));
        }
    }
    public static long pow(long base, int pow, long mod){
        if(pow == 0) return 1;

        long res = pow(base, pow/2, mod);
        res = (res*res)%mod;
        if(pow%2 == 1){
            res = (res*base)%mod;
        }
        return res;
    }
}

import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		boolean[] visited = new boolean[p];
		long answer = 1;
		for(int i=1;i<visited.length;i++){
			if(!visited[i]){
				visited[i] = true;
				long length = 1;
				int j = (k*i)%p;
				while(j != i){
					length++;
					visited[j] = true;
					j = (k*j)%p;
				}
				if(Math.pow(k, length)%p == 1){
					answer = (answer*p)%1000000007;
				}
			}
		}
		System.out.println(answer);
	}
}

import java.util.Scanner;

public class ProblemD {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		int p = input.nextInt();
		int k = input.nextInt();
		if (k == 0){
			System.out.println(1);
			System.exit(0);
		}

		boolean[] hit = new boolean[p];
		int degrees = 0;
		for(int a = 0; a < p; a++){
			if(hit[a] == false){
				degrees++;
				int temp = a;
				while(hit[temp] == false){
					hit[temp] = true;
					temp = (k * temp) % p;
				}
			}
		}
		System.out.println(computePow(p, degrees)); //fix this later
	}

	private static long computePow(int p, int p2) {
		long temp = p;
		for(int a = 0; a < p2; a++){
			temp = temp * p;
			temp = temp % 1000000007;
		}
		return temp;
	}
}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Ideone
{
    static final int MOD = 1000000007;
    static int [] comp;
    public static long pow(int b, int exp) {
        long res = b;
        while(exp != 1) {
            res = ((res%MOD)*(res%MOD))%MOD;
            if(exp%2 == 1)
                res = (res*b)%MOD;
            exp /= 2;
        }
        return res;
    }
    public static int dfs(int i, int p, int k, int num) {
        int next = (int) ((1l*k*i)%p);
        if(comp[next] == -1) {
            comp[next] = num;
            dfs(next, p, k, num);
        }
        return comp[next];
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        if(k == 0)
            System.out.println(pow(p, p-1));
        else if(k == 1)
            System.out.println(pow(p, p));
        else {
            comp = new int[p];
            for(int i = 1;i < p;i++)
                comp[i] = -1;
            int num = 0;
            for(int i = 1;i < p;i++) {
                if(comp[i] == -1) {
                    num++;
                    comp[i] = num;
                    int ret = dfs(i, p, k, num);
                    //System.out.println(ret);
                }
            }
            System.out.println(pow(p, num));
        }
    }
}

import java.util.*;
public class moodular {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		long p=sc.nextLong();
		long k=sc.nextLong();
		long t;
		if (k==0) t=p-1;
		else t=(p-1)/order(k,p);
		long ans=1;
		for (long i=0; i<t; i++) {
			ans=(ans*p)%(1000000007);
		}
		System.out.println(ans);
	}

	public static long order(long k, long p) {
		long n=1;
		long temp=k;
		while (true) {
			if (temp==1) return n;
			else {
				n++;
				temp=(temp*k)%p;
			}
		}
	}

}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {

    static MyScanner   in;
    static PrintWriter out;
//    static Timer timer = new Timer();

    public static void main(String[] args) throws IOException {
        in = new MyScanner();
        out = new PrintWriter(System.out, true);

        int n = in.nextInt();
        int k = in.nextInt();

        int cycles = 0;
        boolean[] was = new boolean[n];
        for (int i = 0; i < n; i++) {
            if (!was[i]) {
                paint(i, n, k, was);
                cycles++;
            }
        }

        out.println(pow(n, cycles - 1, (long) 1e9 + 7));
    }

    private static long pow(long x, int n, long MOD) {
        if (n == 0) return 1;
        if (n % 2 == 1) {
            return (x * pow(x, n - 1, MOD)) % MOD;
        } else {
            return pow((x * x) % MOD, n / 2, MOD);
        }
    }

    private static void paint(int i, int p, int k, boolean[] was) {
        if (was[i]) return;
        was[i] = true;
        paint((int) ((long) i * k % p), p, k, was);
    }
}
class MyScanner {

    public static final String CP1251 = "cp1251";

    private final BufferedReader  br;
    private       StringTokenizer st;
    private       String          last;

    public MyScanner() {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    public MyScanner(String path) throws IOException {
        br = new BufferedReader(new FileReader(path));
    }

    public MyScanner(String path, String decoder) throws IOException {
        br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder));
    }

    String next() throws IOException {
        while (st == null || !st.hasMoreElements())
            st = new StringTokenizer(br.readLine());
        last = null;
        return st.nextToken();
    }

    String next(String delim) throws IOException {
        while (st == null || !st.hasMoreElements())
            st = new StringTokenizer(br.readLine());
        last = null;
        return st.nextToken(delim);
    }

    String nextLine() throws IOException {
        st = null;
        return (last == null) ? br.readLine() : last;
    }

    boolean hasNext() {
        if (st != null && st.hasMoreElements())
            return true;

        try {
            while (st == null || !st.hasMoreElements()) {
                last = br.readLine();
                st = new StringTokenizer(last);
            }
        }
        catch (Exception e) {
            return false;
        }

        return true;
    }

    String[] nextStrings(int n) throws IOException {
        String[] arr = new String[n];
        for (int i = 0; i < n; i++)
            arr[i] = next();
        return arr;
    }

    String[] nextLines(int n) throws IOException {
        String[] arr = new String[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextLine();
        return arr;
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    int[] nextInts(int n) throws IOException {
        int[] arr = new int[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextInt();
        return arr;
    }

    Integer[] nextIntegers(int n) throws IOException {
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextInt();
        return arr;
    }

    int[][] next2Ints(int n, int m) throws IOException {
        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextInt();
        return arr;
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    long[] nextLongs(int n) throws IOException {
        long[] arr = new long[n];
        for (int i = 0; i < n; i++)
            arr[i] = nextLong();
        return arr;
    }

    long[][] next2Longs(int n, int m) throws IOException {
        long[][] arr = new long[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextLong();
        return arr;
    }

    double nextDouble() throws IOException {
        return Double.parseDouble(next().replace(',', '.'));
    }

    double[] nextDoubles(int size) throws IOException {
        double[] arr = new double[size];
        for (int i = 0; i < size; i++)
            arr[i] = nextDouble();
        return arr;
    }

    double[][] next2Doubles(int n, int m) throws IOException {
        double[][] arr = new double[n][m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                arr[i][j] = nextDouble();
        return arr;
    }

    boolean nextBool() throws IOException {
        String s = next();
        if (s.equalsIgnoreCase("true") || s.equals("1"))
            return true;

        if (s.equalsIgnoreCase("false") || s.equals("0"))
            return false;

        throw new IOException("Boolean expected, String found!");
    }
}

import java.io.*;
import java.util.*;

public class modarith {
  private static InputReader in;
  private static PrintWriter out;
  public static int mod = 1000000007;

  public static void main(String[] args) throws IOException {
    in = new InputReader(System.in);
    out = new PrintWriter(System.out, true);

    long p = in.nextInt(), k = in.nextInt();
    if (k == 0) {
      out.println(1);
      out.close();
      System.exit(0);
    } else if (k == 1) {
      long res = 1;
      for(int j = 0; j < p; j++) res = (res * p) % mod;
      out.println(res);
      out.close();
      System.exit(0);
    }
    int cyclen = 0;
    long cur = k;
    do {
      ++cyclen;
      cur = (cur * k) % p;
    } while (cur != k);
    if ((p-1) % cyclen != 0) {
      out.println("AHGIHAG");
      System.exit(1);
    }
    long left = (p-1)/cyclen;
    long res = 1;
    while (left-->0) res = (res * p) % mod;
    out.println(res);
    out.close();
    System.exit(0);
  }

  static class InputReader {
    public BufferedReader reader;
    public StringTokenizer tokenizer;

    public InputReader(InputStream stream) {
      reader = new BufferedReader(new InputStreamReader(stream), 32768);
      tokenizer = null;
    }

    public String next() {
      while (tokenizer == null || !tokenizer.hasMoreTokens()) {
        try {
          tokenizer = new StringTokenizer(reader.readLine());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      return tokenizer.nextToken();
    }

    public int nextInt() {
      return Integer.parseInt(next());
    }
  }

}

import java.io.PrintStream;
import java.util.Scanner;

public class D_Moodular_Arithmetic {
	long pow_mod(long n, long p, long mod) {
		if (p == 1)
			return n % mod;
		long m1 = pow_mod(n, p / 2, mod);
		m1 = m1 * m1;
		m1 %= mod;
		if (p % 2 == 1) {
			m1 *= n;
			m1 %= mod;
		}

		return m1;
	}

	long find_order(long k, long p)
	{
		int order = 1;
		long k_ = k;
		while (k_ != 1)
		{
			k_ *= k;
			k_ %= p;
			order++;

			if (order % 10000 == 0) {
				System.out.println(order);
			}
		}

		return order;
	}

	void solve() {
		Scanner in = new Scanner(System.in);
		long p = in.nextInt();
		long k = in.nextInt();
		in.close();

		long res = 0;

		long mod = 1000000000 + 7;

		if (k == 0) {
			res = pow_mod(p, p - 1, mod);
		}

		if (k == 1) {
			res = pow_mod(p, p, mod);
		}

		if (k > 1) {
			long order_k = find_order(k, p);
			long p1ok = (p - 1) / order_k;
			res = pow_mod(p, p1ok, mod);
		}

		// print the result
		PrintStream out = System.out;
		out.println(res);
	}

	/// the main method
	public static void main(String[] args) {
		D_Moodular_Arithmetic o = new D_Moodular_Arithmetic();
		o.solve();
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        ProblemBMoodularArithmetic solver = new ProblemBMoodularArithmetic();
        solver.solve(1, in, out);
        out.close();
    }

    static class ProblemBMoodularArithmetic {
        int[] parent;
        int mod = (int) 1e9 + 7;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int p = in.readInt();
            long k = in.readInt();
            parent = new int[p];
            for (int i = 0; i < p; i++) parent[i] = i;
            for (int i = 0; i < p; i++) {
                union(i, (int) ((k * i) % p));
            }
            int cnt = 0;
            for (int i = 1; i < p; i++) if (parent[i] == i) cnt++;
            out.println(pow(p, cnt));
        }

        int find(int v) {
            if (parent[v] == v) return v;
            int p = find(parent[v]);
            return parent[v] = p;
        }

        void union(int a, int b) {
            parent[find(a)] = parent[find(b)];
        }

        long pow(long a, long b) {
            long ans = 1;
            while (b > 0) {
                if (b % 2 == 1) ans *= a;
                ans = ans % mod;
                a = (a * a) % mod;
                b /= 2;
            }
            return ans;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

// package codeforces.cf3xx.cf334.div1;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

/**
 * Created by hama_du on 2016/08/17.
 */
public class B {
    private static final long MOD = (long)1e9+7;

    public static void main(String[] args) {
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n = in.nextInt();
        int k = in.nextInt();

        long ans = 1;
        int cnt = 0;
        if (k >= 1) {
            boolean[] visited = new boolean[n];
            int head = 1;
            while (!visited[head]) {
                visited[head] = true;
                cnt++;
                head = (int) (((long) head) * k % n);
            }
        } else {
            cnt = 1;
        }

        for (int g = 0 ; g < (n-1) / cnt ; g++) {
            ans *= n;
            ans %= MOD;
        }

        out.println(ans);
        out.flush();
    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        private int[] nextInts(int n) {
            int[] ret = new int[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextInt();
            }
            return ret;
        }

        private int[][] nextIntTable(int n, int m) {
            int[][] ret = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    ret[i][j] = nextInt();
                }
            }
            return ret;
        }

        private long[] nextLongs(int n) {
            long[] ret = new long[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextLong();
            }
            return ret;
        }

        private long[][] nextLongTable(int n, int m) {
            long[][] ret = new long[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    ret[i][j] = nextLong();
                }
            }
            return ret;
        }

        private double[] nextDoubles(int n) {
            double[] ret = new double[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextDouble();
            }
            return ret;
        }

        private int next() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public char nextChar() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            if ('a' <= c && c <= 'z') {
                return (char) c;
            }
            if ('A' <= c && c <= 'Z') {
                return (char) c;
            }
            throw new InputMismatchException();
        }

        public String nextToken() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            StringBuilder res = new StringBuilder();
            do {
                res.append((char) c);
                c = next();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public int nextInt() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = next();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = next();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = next();
            while (isSpaceChar(c))
                c = next();
            long sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = next();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = next();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            return Double.valueOf(nextToken());
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }

    static void debug(Object... o) {
        System.err.println(Arrays.deepToString(o));
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class D {
	final long MOD = (long)(1e9+7);
	long p,k;
	void readInput() throws NumberFormatException, IOException{
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);
		p = sc.nextLong();
		k = sc.nextLong();
	}

	public static long powmod(long a, long x, long n){
		long res = 1;
		a = a % n;
		while(x>0){
			if ( x % 2 == 1)
				res = (res*a) %n;
			a = (a*a) %n;
			x = x >> 1;
		}
		return res;
	}

	void solve(){
		long ssol = 0;
		if (k==0)
			ssol = powmod(p, p-1, MOD);
		if (k==1)
			ssol = powmod(p, p, MOD);
		else  if (k==p-1){
			ssol = powmod(p, (p-1)/2, MOD);
		}
		else
			ssol = p;
		System.out.println(ssol);
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		D a = new D();
		a.readInput();
		a.solve();
	}

}

import java.util.*;

public class D334 {
	static long mod;
	public static void main(String[] args) {

		Scanner qwe = new Scanner(System.in);

		long p = qwe.nextLong();
		long k = qwe.nextLong();

		long[] maps = new long[(int)p];
		for (int i = 0; i < maps.length; i++) {
			maps[i] = (i*k)%p;
			//System.out.println("x: " + i + " xp: " + maps[i]);
		}

		HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();

		boolean[] been = new boolean[maps.length];

		for(int i =0; i < maps.length; i++){
			if(!been[i]){
				int size = 1;
				been[i] = true;

				long at = i;
				while(true){
					at = maps[(int)at];
					if(been[(int)at]){
						break;
					}

					been[(int)at] = true;
					size++;

				}
				if(!hm.containsKey(size)) hm.put(size, 0);
				hm.put(size, hm.get(size)+1);

			}
		}

		long ans = 1;
		mod = (int)(1e9+7);

		for(int size : hm.keySet()){
			int amount = hm.get(size);
			long mult = 0;
			if(hm.containsKey(1)){
				mult += hm.get(1);
			}

			if(size % 2 == 0){
				if(hm.containsKey(2)){
					mult += hm.get(2)*2;
				}
			}

			for(int div = 3; div <= Math.sqrt(size)+1; div += 2){
				if(size % div ==0 && hm.containsKey(div)){
					mult += hm.get(div)*div;
					mult %= mod;

					int other = size/div;
					if(other > div && hm.containsKey(other)){
						mult += hm.get(other)*other;
						mult %= mod;
					}

				}
			}

			mult = fastexpo(mult,amount);
			ans *= mult;
			ans %= mod;
		}

		System.out.println(ans);

		qwe.close();
	}

	static long fastexpo(long b, long pow){
		if(pow == 0) return 1l;

		long temp = fastexpo(b,pow/2);
		temp *= temp;
		temp %= mod;
		if(pow % 2 == 1) temp *= b;

		return temp%mod;

	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author ilyakor
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        static final long mod = 1000 * 1000 * 1000 + 7;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int p = in.nextInt();
            int k = in.nextInt();
            if (k == 0) {
                out.printLine(1);
                return;
            }
            int cnt = 0;
            long cur = 1;
            do {
                ++cnt;
                cur = (cur * (long) k) % p;
            } while (cur != 1);
            Assert.assertTrue((p - 1) % cnt == 0);
            long r = (p - 1) / cnt;
            long res = IntegerUtils.pow(p, r, mod);
            out.printLine(res);
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buffer = new byte[10000];
        private int cur;
        private int count;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public static boolean isSpace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int read() {
            if (count == -1) {
                throw new InputMismatchException();
            }
            try {
                if (cur >= count) {
                    cur = 0;
                    count = stream.read(buffer);
                    if (count <= 0)
                        return -1;
                }
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            return buffer[cur++];
        }

        public int readSkipSpace() {
            int c;
            do {
                c = read();
            } while (isSpace(c));
            return c;
        }

        public int nextInt() {
            int sgn = 1;
            int c = readSkipSpace();
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = read();
            } while (!isSpace(c));
            res *= sgn;
            return res;
        }

    }

    static class Assert {
        public static void assertTrue(boolean flag) {
//        if (!flag)
//        while (true);
            if (!flag)
                throw new AssertionError();
        }

    }

    static class IntegerUtils {
        public static long pow(long x, long y, long mod) {
            x %= mod;
            long res = 1;
            while (y > 0) {
                if (y % 2 == 1) {
                    --y;
                    res = BigInteger.valueOf(res).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
                } else {
                    y /= 2;
                    x = BigInteger.valueOf(x).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
                }
            }
            return res % mod;
        }

    }
}

import java.io.*;
import java.util.*;

public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int p = nextInt();
        int k = nextInt();
        long ans = 1;
        boolean used[] = new boolean[p];
        for(int i = 1;i < p;i++) {
            int v = i;
            if (!used[i]) {
                while (!used[v]) {
                    used[v] = true;
                    v = (v * k) % p;
                }
                ans = (ans * p) % inf;
            }
        }

        if (k <= 1) ans = (ans * p) % inf;
        pw.println(ans);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Div2_334_D
{
    static final int MOD = 1000000007;
    static int [] comp;
    public static long pow(int b, int exp) {
        long res = b;
        while(exp != 1) {
            res = ((res%MOD)*(res%MOD))%MOD;
            if(exp%2 == 1)
                res = (res*b)%MOD;
            exp /= 2;
        }
        return res;
    }
    public static int dfs(int i, int p, int k, int num) {
        int next = (int) ((1l*k*i)%p);
        //System.out.println(i+" "+next);
        if(comp[next] == -1) {
            comp[next] = num;
            comp[next] = Math.min(comp[next], dfs(next, p, k, num));
        }
        return comp[next];
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        if(k == 0)
            System.out.println(pow(p-1, p-1));
        else if(k == 1)
            System.out.println(pow(p, p));
        else {
            comp = new int[p];
            for(int i = 1;i < p;i++)
                comp[i] = -1;
            int num = 0;
            for(int i = 1;i < p;i++) {
                if(comp[i] == -1) {
                    comp[i] = num+1;
                    int ret = dfs(i, p, k, num+1);
                    comp[i] = Math.min(comp[i], ret);
                    //System.out.println(ret);
                    if(ret > num) {
                        //System.out.println(i+" "+num+" "+ret);
                        num++;
                    }
                }
            }
            System.out.println(pow(p, num));
        }
    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
//     Test.testing();
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.flush();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    ArrayList<ArrayList<Integer>> gr1;
    ArrayList<ArrayList<Integer>> gr2;
    boolean[] visit;
    //

    public void solve() {
        int[] l = io.readIntArray();
        long p = l[0], k = l[1];
        long res = 1;
        long mod = 1000_000_007;
        visit = new boolean[(int) p];
        for (int i = 1; i < p; i++) {
            int h = i;
            boolean need = false;
            while (!visit[h]) {
                need = true;
                visit[h] = true;
                h = (int) (k * h % p);
            }
            if(need) res = (res * p) % mod;
        }
        io.writeLine(res + "");
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long readLong() {
        return Long.parseLong(this.readLine());
    }
    public int readInt() {
        return Integer.parseInt(this.readLine().trim());
    }
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split(" ");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author George Marcus
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        private static final long MOD = 1000000007;
        boolean[] v;
        boolean[] v2;
        ArrayList<Integer>[] A;
        int[] to;
        int[] stack;
        int[] Q;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int P = in.readInt();
            int K = in.readInt();

            A = new ArrayList[P];
            for (int i = 0; i < P; i++) {
                A[i] = new ArrayList<>();
            }
            to = new int[P];

            long[] pow = new long[P + 1];
            pow[0] = 1;
            for (int i = 1; i <= P; i++) {
                pow[i] = pow[i - 1] * K % P;
            }

            for (int x = 0; x < P; x++) {
                int y = (int) ((long) x * K % P);
                A[x].add(y);
                A[y].add(x);
                to[x] = y;
            }

            stack = new int[P + 1];
            Q = new int[P + 1];
            v = new boolean[P];
            v2 = new boolean[P];
            long ans = 0;
            for (int i = 0; i < P; i++) {
                if (!v[i]) {
                    int len = handleComp(i);
                    bfs(i);
                    long kpow = pow[len];
                    if (kpow == 1) {
                        ans++;
                    }
                }
            }

            ans = fastPow(P, (int) ans);
            out.println(ans);
        }

        private long fastPow(long a, int p) {
            long ret = 1;
            while (p > 0) {
                if ((p & 1) > 0) {
                    ret = ret * a % MOD;
                }
                a = a * a % MOD;
                p >>= 1;
            }
            return ret;

        }

        private void bfs(int start) {
            int left = 0;
            int right = 0;
            v[start] = true;
            Q[right++] = start;

            while (left < right) {
                int node = Q[left++];
                for (int x : A[node]) {
                    if (!v[x]) {
                        v[x] = true;
                        Q[right++] = x;
                    }
                }
            }
        }

        private int handleComp(int start) {
            int p = 0;
            stack[p++] = start;
            while (p > 0) {
                int node = stack[p - 1];
                v2[node] = true;
                int x = to[node];
                if (v2[x]) {
                    int len = 1;
                    while (stack[p - 1] != x) {
                        len++;
                        p--;
                    }
                    return len;
                }
                stack[p++] = x;
            }
            return -1;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

/*
 * k = 0, f(0) = 0, p^(p-1)
 * k = 1, p^p
 * k = 2, p
 *  p = 3, f(2x mod 3) = 2f(x) mod 3,
 *      f(1) = 1, f(2) = 2
 *      f(2) = 2, f(1) = 1
 *  p = 5, f(2x mod 5) = 2f(x) mod 5,
 *      f(1) = 1, f(2) = 2, f(3) = 3, f(4) = 4
 *      f(1) = 2, f(2) = ...
 * k = 3, p
 *  p = 5, f(3x mod 5) = 3f(x) mod 5,
 *      f(1) = 1, f(3) = 3, f(
 * k = 4, p*p
 *  p = 5, f(4x mod 5) = 4f(x) mod 5,
 *     f(1) = 1, f(4) = 4  f(2) = 1, f(3) =  ,
 *  p = 7, f(4x mod 7) = 4f(x) mod 7,
 *     f(1),f(4),f(2),   f(3)f(5)
 *
 * k = 5, p
 * k = 6, 1,6  2,5 3,4
 * /
 */
import java.util.Scanner;
import java.util.Arrays;
import static java.lang.Math.toIntExact;

public class D {
    private static class mergeSet {
        private int set_size;
        private int[] parent;

        mergeSet(int size) {
            set_size = size;
            parent = new int[size];
            Arrays.fill(parent, -1);
        }

        int find(int x) {
            if(parent[x] < 0) return x; else return find(parent[x]);
        }

        void merge(int x, int y) {
            int p = find(x);
            int q = find(y);
            if (p == q) {
                return;
            }
            parent[q] += parent[p];
            parent[p] = q;
        }

        int count() {
            int ans=0;
            for(int i=1;i<set_size;i++) {
                if(parent[i]<0) ans ++;
            }
            return ans;
        }
    }

    public static void main(String[] args) {
        Scanner scanIn = new Scanner(System.in);
        int p = scanIn.nextInt();
        int k = scanIn.nextInt();
        int cluster;
        if (k <= 1) {
            cluster = p - 1 + k;
        } else {
            mergeSet m = new mergeSet(p);
            for(int i = 1;i < p;i ++) {
                long temp = i;
                temp *= k;
                temp %= p;
                m.merge(i, toIntExact(temp));
            }
            cluster = m.count();
        }
        int ans = p;
        final int MOD = 1000000007;
        for(int i=1;i<cluster;i++) {
            ans = (ans * p) % MOD;
        }
        System.out.println(ans);
    }
}

/*package whatever //do not write package name here */

import java.io.*;

public class Main {
    final static double mod = 1e9 + 7;
	public static void main (String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input = bf.readLine().split(" ");
		long p = Long.parseLong(input[0]);
		long k = Long.parseLong(input[1]);
		long order = 1;
		long temp = k;

		if (k == 0)
		    System.out.println((int)Math.pow(p, p - 1));
		else {
    	    while (temp != 1) {
    	        temp = (k * temp) % p;
    	        order++;
    	    }
		System.out.println(((int)Math.pow(p, (p - 1)/order)) % (int) mod);

		}

	}
}

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by chavit on 01.12.2015.
 */
public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if (!BigInteger.valueOf(n).isProbablePrime(25)) {
            throw new AssertionError();
        }
        int k = in.nextInt();
        int[] multiplier = new int[n];
        long res = 1, mod = (long)(1e+9+7);
        for (int i = 1; i < n; i++) {
            int pos = i;
            if (multiplier[pos] != 0) {
                continue;
            }
            res = (res * n) % mod;
            while (multiplier[pos] != 1) {
                multiplier[pos] = 1;
                pos = (int)(((long)pos * (long)k) % (long)n);
            }
        }
        System.out.println(res);
    }
}

import java.math.BigInteger;
import java.util.Scanner;

public class D {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		String[] firstLine = s.nextLine().split(" ");

		boolean[] done = new boolean[Integer.parseInt(firstLine[0])];
		int K = Integer.parseInt(firstLine[1]);

		BigInteger ways = new BigInteger("1");

		if (K != 0) {

		int[] cycles = new int[done.length];

		for (int i = 1; i < done.length; i++) {

			if (!done[i]) {

				done[i] = true;
				long cycleLength = 1;
				long start = (i * (long) K) % done.length;

				while (start != i) {

					done[(int) start] = true;
					start *= K;
					start %= done.length;
					cycleLength++;

				}

				cycles[(int) cycleLength]++;

			}

		}
		long way = 1;
		for (int i = 0; i < cycles.length; i++) {

			if (cycles[i] != 0) {

				for (int j = 0; j < cycles[i]; j++) {

					way *= cycles[i] * i + 1;
					way %= 1000000007;

				}

			}

		}
		System.out.println(way);

		}else{

			int p = done.length;
			ways = new BigInteger(String.valueOf(p));
			ways = ways.modPow(new BigInteger(String.valueOf(p - 1)), new BigInteger("1000000007"));

			System.out.println(ways);

		}

		s.close();
		System.exit(0);

	}

}

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by chavit on 01.12.2015.
 */
public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        int[] multiplier = new int[n];
        long res = 1, mod = (long)(1e+9+7);
        for (int i = 1; i < n; i++) {
            int pos = i;
            if (multiplier[pos] != 0) {
                continue;
            }
            res = (res * n) % mod;
            while (multiplier[pos] != 1) {
                multiplier[pos] = 1;
                pos = (int)(((long)pos * (long)k) % (long)n);
                if (pos == 0) {
                    System.out.println(1);
                    return;
                }
            }
        }
        System.out.println(res);
    }
}

import java.util.*;

public class D {

    public static void main(String[] args) {
    	Scanner s = new Scanner(System.in);
    	int p, k;
    	p = s.nextInt();
    	k = s.nextInt();
    	if(k == 0) {
    		long ans = 1;
    		for(int i=1; i<p; i++)
    			ans = (ans*p)%1000000007;
    		System.out.println(ans);
    		System.exit(0);
    	}
    	boolean[] graph = new boolean[p];
    	long ans = 1;
    	for(int i=1; i<p; i++) {
    		if(!graph[i]) {
    			long tmp = i;
    			int rot = 0;
    			do {
    				graph[(int)tmp] = true;
    				tmp = (tmp*k)%p;
    				rot++;
    			} while(tmp != i);
    			if(rot != 1)
	    			ans = (ans*p)%1000000007;
	    		else ans = (((ans*p)%1000000007)*p)%1000000007;
    		}
    	}
    	System.out.println(ans);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class MoodularArithmetic {

	public static void main(String[] args) throws IOException {

		Scanner sc = new Scanner(System.in);

		int p = sc.nextInt();

		int k = sc.nextInt();

		UnionFind uf = new UnionFind(p);

		for (int i = 0; i < p; i++) {
			uf.unionSet(i,(int) (1L *k * i % p));
		}

		System.out.println(modPow(p, uf.numSets-1, (int) 1e9 + 7));

	}

	static long modPow(long a, int e, int mod)	// O(log e)
	{
		a %= mod;
		long res = 1;
		while(e > 0)
		{
			if((e & 1) == 1)
				res = (res * a) % mod;
			a = (a * a) % mod;
			e >>= 1;
		}
		return res;
}

	static public class UnionFind {
		int[] p, rank, setSize;
		int numSets;

		public UnionFind(int N)
		{
			p = new int[numSets = N];
			rank = new int[N];
			setSize = new int[N];
			for (int i = 0; i < N; i++) {  p[i] = i; setSize[i] = 1; }
		}

		public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }

		public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }

		public void unionSet(int i, int j)
		{
			if (isSameSet(i, j))
				return;
			numSets--;
			int x = findSet(i), y = findSet(j);
			if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
			else
			{	p[x] = y; setSize[y] += setSize[x];
				if(rank[x] == rank[y]) rank[y]++;
			}
		}

		public int numDisjointSets() { return numSets; }

		public int sizeOfSet(int i) { return setSize[findSet(i)]; }
	}

	static class Scanner

	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}

		public int nextInt() throws IOException {return Integer.parseInt(next());}

		public long nextLong() throws IOException {return Long.parseLong(next());}

		public String nextLine() throws IOException {return br.readLine();}

		public double nextDouble() throws IOException
		{
			String x = next();
			StringBuilder sb = new StringBuilder("0");
			double res = 0, f = 1;
			boolean dec = false, neg = false;
			int start = 0;
			if(x.charAt(0) == '-')
			{
				neg = true;
				start++;
			}
			for(int i = start; i < x.length(); i++)
				if(x.charAt(i) == '.')
				{
					res = Long.parseLong(sb.toString());
					sb = new StringBuilder("0");
					dec = true;
				}
				else
				{
					sb.append(x.charAt(i));
					if(dec)
						f *= 10;
				}
			res += Long.parseLong(sb.toString()) / f;
			return res * (neg?-1:1);
		}

		public boolean ready() throws IOException {return br.ready();}

	}
}

import java.util.Scanner;

public class Main {
	static int mod[];
	public static void build(int k,int p){
		mod = new int[p];
		mod[0] = 1;
		for(int i=1;i<p;i++){
			mod[i] = (mod[i-1]*k)%p;
		}
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		build(k,p);
		boolean[] visited = new boolean[p];
		long answer = 1;
		if(k==0){

		}
		else{
			for(int i=1;i<visited.length;i++){
				if(!visited[i]){
					visited[i] = true;
					int length = 1;
					int j = (k*i)%p;
					while(j != i){
						length++;
						visited[j] = true;
						j = (k*j)%p;
					}
					if(mod[length] == 1){
						answer = (answer*p)%1000000007;
					}
				}
			}
		}

		System.out.println(answer);
	}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
//     Test.testing();
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.flush();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    ArrayList<ArrayList<Integer>> gr1;
    ArrayList<ArrayList<Integer>> gr2;
    boolean[] visit;
    //

    public void solve() {
        int[] l = io.readIntArray();
        long p = l[0], k = l[1];
        long res = 1;
        long mod = 1000_000_007;
        visit = new boolean[(int) p];
        for (int i = 1; i < p; i++) {
            int h = i;
            boolean need = false;
            while (!visit[h]) {
                need = true;
                visit[h] = true;
                h = (int) (k * h % p);
            }
            if(need) res = (res * p) % mod;
        }
        if(k<2)res = (res*p)%mod;
        io.writeLine(res + "");
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long readLong() {
        return Long.parseLong(this.readLine());
    }
    public int readInt() {
        return Integer.parseInt(this.readLine().trim());
    }
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split(" ");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
}

import java.util.Scanner;

public class MoodularArithmetic {
    private static final int MOD = 1000000007;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        int res;

        if (k == 0) {
            res = pow(p, p - 1);
        } else if (k == 1) {
            res = pow(p, p);
        } else {
            int groups = 0;
            boolean[] n = new boolean[p];
            n[0] = true;
            int i = 1;
            while (i < p) {
                if (n[i]) {
                    i++;
                    continue;
                } else {
                    groups++;
                    n[i] = true;
                }

                int j = i;
                while (true) {
                    j = (j * k) % p;
                    if (n[j]) {
                        break;
                    } else {
                        n[j] = true;
                    }
                }
            }
            res = pow(p, groups);
        }
        System.out.println(res);
    }

    private static int pow(int base, int pow) {
        int res = 1;
        for (int i = 0; i < pow; i++) {
            res = (res * base) % MOD;
        }
        return res;
    }
}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Ideone
{
    static final int MOD = 1000000007;
    static int [] comp;
    public static long pow(int b, int exp) {
        long res = b;
        while(exp != 1) {
            res = ((res%MOD)*(res%MOD))%MOD;
            if(exp%2 == 1)
                res = (res*b)%MOD;
            exp /= 2;
        }
        return res;
    }
    public static int dfs(int i, int p, int k, int num) {
        int next = (int) ((1l*k*i)%p);
        if(comp[next] == -1) {
            comp[next] = num;
            dfs(next, p, k, num);
        }
        return comp[next];
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        if(k == 0)
            System.out.println(pow(p, p-1));
        else if(k == 1)
            System.out.println(pow(p, p));
        else {
            comp = new int[p];
            for(int i = 1;i < p;i++)
                comp[i] = -1;
            int num = 0;
            for(int i = 1;i < p;i++) {
                if(comp[i] == -1) {
                    num++;
                    comp[i] = num;
                    int ret = dfs(i, p, k, num);
                    //System.out.println(ret);
                }
            }
            System.out.println(pow(p, num));
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Agostinho Junior (junior94)
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		OutputWriter out = new OutputWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}

	static class TaskB {
		public TaskB() {
		/*
		for (int p = 3; p <= 10; p++) if (XMath.isPrime(p)) {
			for (int k = 0; k < p; k++) {
				System.out.printf("p: %d, k: %d\n", p, k);
				printIn(p, k);
				System.out.println("\n================");
			}
			System.out.println("================");
		}*/
		}

		public void solve(int testNumber, InputReader in, OutputWriter out) {
			int p = in.readInt();
			int k = in.readInt();

			if (k == 0) {
				out.println(XMath.modPow(p, p - 1));
				return;
			}

			//printIn(p, k);
			int[] sizeCount = new int[p + 1];
			boolean[] visited = new boolean[p];
			Set<Integer> set = new HashSet<>();
			for (int i = 0; i < p; i++)
				if (!visited[i]) {
					int node = i;
					set.clear();
					while (!visited[node]) {
						set.add(node);
						visited[node] = true;
						node = (int) XMath.mod(node * k, p);
					}
					sizeCount[set.size()]++;
				}

			long res = 1;

			sizeCount[1]--;

			for (int size = 1; size < sizeCount.length; size++) {
				//.out.printf("sizeCount[%d] = %d\n", size, sizeCount[size]);
				res = XMath.mod(res * XMath.modPow(XMath.mod(size * sizeCount[size] + 1), sizeCount[size]));
			}

			out.println(res);
		}

	}

	static class InputReader {
		private BufferedReader input;
		private StringTokenizer line = new StringTokenizer("");

		public InputReader() {
			this(System.in);
		}

		public InputReader(InputStream in) {
			input = new BufferedReader(new InputStreamReader(in));
		}

		public InputReader(String s) {
			try {
				input = new BufferedReader(new FileReader(s));
			} catch (IOException io) {
				io.printStackTrace();
				System.exit(0);
			}
		}

		public void fill() {
			try {
				if (!line.hasMoreTokens()) {
					line = new StringTokenizer(input.readLine());
				}
			} catch (IOException io) {
				io.printStackTrace();
				System.exit(0);
			}
		}

		public int readInt() {
			fill();
			return Integer.parseInt(line.nextToken());
		}

	}

	static class OutputWriter {
		private PrintWriter output;

		public OutputWriter() {
			this(System.out);
		}

		public OutputWriter(OutputStream out) {
			output = new PrintWriter(out);
		}

		public OutputWriter(Writer writer) {
			output = new PrintWriter(writer);
		}

		public void println(Object o) {
			output.println(o);
		}

		public void close() {
			output.close();
		}

	}

	static class XMath {
		public static final long DEFAULT_MOD = (long) 1e9 + 7;
		public static long MOD = DEFAULT_MOD;

		public static long mod(long n, long MOD) {
			if (n < MOD) {
				if (n < 0) {
					return mod(MOD - mod(-n, MOD), MOD);
				}
				return n;
			}
			return n % MOD;
		}

		public static long mod(long n) {
			return mod(n, MOD);
		}

		public static long modPow(long x, long n, long mod) {
			long res = 1;
			x = mod(x, mod);
			while (n > 0) {
				if ((n & 1) > 0) {
					res = mod(res * x, mod);
				}
				x = mod(x * x, mod);
				n >>= 1;
			}
			return res;
		}

		public static long modPow(long x, long n) {
			return modPow(x, n, MOD);
		}

	}
}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Div2_334_D
{
    static final int MOD = 1000000007;
    static int [] comp;
    public static long pow(int b, int exp) {
        long res = b;
        while(exp != 1) {
            res = ((res%MOD)*(res%MOD))%MOD;
            if(exp%2 == 1)
                res = (res*b)%MOD;
            exp /= 2;
        }
        return res;
    }
    public static int dfs(int i, int p, int k, int num) {
        int next = (int) ((1l*k*i)%p);
        //System.out.println(i+" "+next);
        if(comp[next] == -1) {
            comp[next] = num;
            comp[next] = Math.min(comp[next], dfs(next, p, k, num));
        }
        return comp[next];
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        int k = sc.nextInt();
        if(k == 0)
            System.out.println(pow(p-1, p-1));
        else if(k == 1)
            System.out.println(pow(p, p));
        else {
            comp = new int[p];
            for(int i = 1;i < p;i++)
                comp[i] = -1;
            int num = 0;
            for(int i = 1;i < p;i++) {
                if(comp[i] == -1) {
                    comp[i] = num+1;
                    int ret = dfs(i, p, k, num+1);
                    comp[i] = Math.min(comp[i], ret);
                    //System.out.println(ret);
                    if(ret > num) {
                        //System.out.println(i+" "+num+" "+ret);
                        num++;
                    }
                }
            }
            System.out.println(pow(p, num));
        }
    }
}

import java.util.Scanner;

public class ProblemD {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);
		int p = input.nextInt();
		int k = input.nextInt();
		if (k == 0){
			System.out.println(1);
			System.exit(0);
		}

		boolean[] hit = new boolean[p];
		int degrees = 0;
		for(int a = 0; a < p; a++){
			if(hit[a] == false){
				degrees++;
				int temp = a;
				while(hit[temp] == false){
					hit[temp] = true;
					temp = (k * temp) % p;
				}
			}
		}
		System.out.println(computePow(p, degrees)); //fix this later
	}

	private static long computePow(int p, int p2) {
		long temp = p;
		for(int a = 0; a < p2; a++){
			temp = temp * p;
			temp = temp % 1000000007;
		}
		return temp;
	}
}

import java.io.PrintStream;
import java.util.Scanner;

public class D_Moodular_Arithmetic {
	long pow_mod(long n, long p, long mod) {
		if (p == 1)
			return n % mod;
		long m1 = pow_mod(n, p / 2, mod);
		m1 = m1 * m1;
		m1 %= mod;
		if (p % 2 == 1) {
			m1 *= n;
			m1 %= mod;
		}

		return m1;
	}

	long find_order(long k, long p)
	{
		int order = 1;
		long k_ = k;
		while (k_ != 1)
		{
			k_ *= k;
			k_ %= p;
			order++;

			if (order % 10000 == 0) {
				System.out.println(order);
			}
		}

		return order;
	}

	void solve() {
		Scanner in = new Scanner(System.in);
		long p = in.nextInt();
		long k = in.nextInt();
		in.close();

		long res = 0;

		long mod = 1000000000 + 7;

		if (k == 0) {
			res = pow_mod(p, p - 1, mod);
		}

		if (k == 1) {
			res = pow_mod(p, p, mod);
		}

		if (k > 1) {
			long order_k = find_order(k, p);
			long p1ok = (p - 1) / order_k;
			res = pow_mod(p, p1ok, mod);
		}

		// print the result
		PrintStream out = System.out;
		out.println(res);
	}

	/// the main method
	public static void main(String[] args) {
		D_Moodular_Arithmetic o = new D_Moodular_Arithmetic();
		o.solve();
	}
}

import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by chavit on 01.12.2015.
 */
public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        int[] multiplier = new int[n];
        long res = 1, mod = (long)(1e+9+7);
        for (int i = 1; i < n; i++) {
            int pos = i;
            if (multiplier[pos] != 0) {
                continue;
            }
            res = (res * n) % mod;
            while (multiplier[pos] != 1) {
                multiplier[pos] = 1;
                pos = (int)(((long)pos * (long)k) % (long)n);

            }
        }
        System.out.println(res);
    }
}

import java.io.*;

public class Main {
    final static double mod = 1e9 + 7;
	public static void main (String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input = bf.readLine().split(" ");
		long p = Long.parseLong(input[0]);
		long k = Long.parseLong(input[1]);
		long order = 1;
		long temp = k;

		if (k == 0)
		    System.out.println((int)Math.pow(p, p - 1));
		else {
    	    while (temp != 1) {
    	        temp = (k * temp) % p;
    	        order++;
    	    }

    	    if (k == 1)
		        System.out.println((((int)Math.pow(p, (p - 1)/order)) % (int) mod)*p);
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class D {
	final long MOD = (long)(1e9+7);
	long p,k;
	void readInput() throws NumberFormatException, IOException{
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);
		p = sc.nextLong();
		k = sc.nextLong();
	}

	public static long powmod(long a, long x, long n){
		long res = 1;
		a = a % n;
		while(x>0){
			if ( x % 2 == 1)
				res = (res*a) %n;
			a = (a*a) %n;
			x = x >> 1;
		}
		return res;
	}

	void solve(){
		long ssol = 0;
		if (k==0)
			ssol = powmod(p, p-1, MOD);
		if (k==1)
			ssol = powmod(p, p, MOD);
		else  if (k==p-1){
			ssol = powmod(p, (p-1)/2, MOD);
		}
		else
			ssol = p;
		System.out.println(ssol);
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		D a = new D();
		a.readInput();
		a.solve();
	}

}

import java.util.*;
import java.io.*;

public class B {
    FastScanner in;
    PrintWriter out;
    boolean[] used;
    long[] pow;
    static long p, k;
    final long MOD = (long) 1e9 + 7;
    static int col = 0;

    public void dfs(long v) {
        used[(int) v] = true;
        if (!used[(int) ((k * v) % p)]) {
            dfs((k * v) % p);
        }
    }

    public void solve() throws IOException {
        p = in.nextInt();
        k = in.nextInt();
        used = new boolean[(int) p];
        pow = new long[(int) p + 1];
        pow[0] = 1;
        for (int i = 0; i < p; i++) {
            pow[i + 1] = (pow[i] * p) % MOD;
        }
        int ans = 0;
        for (int i = 1; i < p; i++) {
            if (!used[i]) {
                dfs(i);
                ans++;
            }
        }
        out.println(pow[ans]);
    }

    public void run() {
        try {
            in = new FastScanner(System.in);
            out = new PrintWriter(System.out);
            solve();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream f) {
            br = new BufferedReader(new InputStreamReader(f));
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }

    public static void main(String[] arg) {
        new B().run();
    }
}

import java.io.*;
import java.util.*;
public class B603 {
public static void main(String[] args) throws IOException {
    input.init(System.in);
    PrintWriter out = new PrintWriter(System.out);
    int p = input.nextInt(), k = input.nextInt();
    boolean[] used = new boolean[p];
    used[0] = true;
    int cyc = 1;
    for(int i = 1; i<p; i++)
    {
        if(used[i]) continue;
        int at = i;
        while(true)
        {
            if(used[at]) break;
            used[at] = true;
            at = (int) ((long)at*k);
            at %= p;
        }
        cyc++;
    }
    if(k == 0)
    {
        out.println(pow(p-1,p));
    }
    else if(p == 1)
    {
        out.println(pow(p, cyc));
    }
    else
    {
        out.println(pow(p, cyc-1));
    }
    out.close();
}
static long pow(long n, long p)
{
    if(p == 0) return 1;
    if(p%2 == 0)
    {
        long sqrt = pow(n,p>>1);
        return (sqrt*sqrt)%1000000007;
    }
    return (n * pow(n,p-1))%1000000007;
}
public static class input {
    static BufferedReader reader;
    static StringTokenizer tokenizer;

    static void init(InputStream input) {
    reader = new BufferedReader(new InputStreamReader(input));
    tokenizer = new StringTokenizer("");
    }

    static String next() throws IOException {
    while (!tokenizer.hasMoreTokens())
        tokenizer = new StringTokenizer(reader.readLine());
    return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
    return Integer.parseInt(next());
    }

    static double nextDouble() throws IOException {
    return Double.parseDouble(next());
    }

    static long nextLong() throws IOException {
    return Long.parseLong(next());
    }
}
}

import java.io.*;

public class Main {
    final static long mod = (long) 1e9 + 7;

    public static long pow(long x, long n) {
        long ans = 1;
        while(n != 0) {
            if(n%2 == 1)
                ans *= x;
                ans %= mod;
            n/= 2;
            x *= x;
            x %= mod;
        }
        return ans % mod;
    }

	public static void main (String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input = bf.readLine().split(" ");
		long p = Integer.parseInt(input[0]);
		long k = Integer.parseInt(input[1]);
		long order = 1;
		long temp = k;

		if (k == 0)
		    System.out.println((int) pow(p, p - 1));
		if (k == 1)
		    System.out.println(((pow(p,p))));
		else {
    	    while (order < p) {
    	        if(temp == 1)
    	            break;
    	        temp = ((k % p) * (temp % p)) % p;
    	        order++;
    	    }
		    System.out.println(((pow(p, (p - 1)/order))));
		}
	}
}

import java.util.*;
import java.lang.*;
import java.io.*;

public class Div2_334_D
{
	static final int MOD = 1000000007;
	static int [] comp;
	public static long pow(int b, int exp) {
		long res = b;
		while(exp != 1) {
			res = ((res%MOD)*(res%MOD))%MOD;
			if(exp%2 == 1)
				res = (res*b)%MOD;
			exp /= 2;
		}
		return res;
	}
	public static int dfs(int i, int p, int k, int num) {
		int next = (int) ((1l*k*i)%p);
		//System.out.println(i+" "+next);
		if(comp[next] == -1) {
			comp[next] = num;
			comp[next] = Math.min(comp[next], dfs(next, p, k, num));
		}
		return comp[next];
	}
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		int p = sc.nextInt();
		int k = sc.nextInt();
		if(k == 0)
			System.out.println(pow(p, p-1));
		else if(k == 1)
			System.out.println(pow(p, p));
		else {
			comp = new int[p];
			for(int i = 1;i < p;i++)
				comp[i] = -1;
			int num = 0;
			for(int i = 1;i < p;i++) {
				if(comp[i] == -1) {
					comp[i] = num+1;
					int ret = dfs(i, p, k, num+1);
					comp[i] = Math.min(comp[i], ret);
					//System.out.println(ret);
					if(ret > num) {
						//System.out.println(i+" "+num+" "+ret);
						num++;
					}
				}
			}
			System.out.println(pow(p, num));
		}
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author xwchen
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Scanner in = new Scanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public static int cnt;
        public static int N = 1000002;
        public static Edge[] edges = new Edge[1000000 * 2 + 5];
        public static int[] head = new int[N];
        public static boolean[] vis = new boolean[N];

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            long p = in.nextLong();
            long k = in.nextLong();
            long mod = 1000000007;
            Arrays.fill(head, -1);
            Arrays.fill(vis, false);
            for (int i = 0; i < N * 2; ++i) {
                edges[i] = new Edge();
            }
            cnt = 0;
            long ret = 1;
            for (int i = 1; i < p; ++i) {
                addEdge((int) (k * i % p), i);
                addEdge(i, (int) (k * i % p));
            }
            int count = 0;
            for (int i = 1; i < p; ++i) {
                if (!vis[i]) {
                    dfs(i, i);
                    ++count;
                }
            }
            //out.println("p="+p+" cnt = "+count);
            for (int i = 0; i < count; ++i) {
                ret = ret * p % mod;
            }
            out.println(ret);
        }

        public static void dfs(int u, int pre) {
            vis[u] = true;
            for (int e = head[u]; e != -1; e = edges[e].pre) {
                int v = edges[e].v;
                if (!vis[v]) {
                    dfs(v, u);
                }
            }
        }

        public static void addEdge(int u, int v) {
            edges[cnt].u = u;
            edges[cnt].v = v;
            edges[cnt].pre = head[u];
            head[u] = cnt++;
        }

        class Edge {
            int u;
            int v;
            int pre;

        }

    }
}

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by chavit on 01.12.2015.
 */
public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        if (!BigInteger.valueOf(n).isProbablePrime(25)) {
            throw new AssertionError();
        }
        int k = in.nextInt();
        int[] multiplier = new int[n];
        long res = 1, mod = (long)(1e+9+7);
        for (int i = 1; i < n; i++) {
            int pos = i;
            if (multiplier[pos] != 0) {
                continue;
            }
            res = (res * n) % mod;
            while (multiplier[pos] != 1) {
                multiplier[pos] = 1;
                pos = (int)(((long)pos * (long)k) % (long)n);
            }
        }
        System.out.println(res);
    }
}

import java.util.*;

public class D334 {
	static long mod;
	public static void main(String[] args) {

		Scanner qwe = new Scanner(System.in);

		long p = qwe.nextLong();
		long k = qwe.nextLong();

		long[] maps = new long[(int)p];
		for (int i = 0; i < maps.length; i++) {
			maps[i] = (i*k)%p;
			//System.out.println("x: " + i + " xp: " + maps[i]);
		}

		HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();

		boolean[] been = new boolean[maps.length];

		for(int i =0; i < maps.length; i++){
			if(!been[i]){
				int size = 1;
				been[i] = true;

				long at = i;
				while(true){
					at = maps[(int)at];
					if(been[(int)at]){
						break;
					}

					been[(int)at] = true;
					size++;

				}
				if(!hm.containsKey(size)) hm.put(size, 0);
				hm.put(size, hm.get(size)+1);

			}
		}

		long ans = 1;
		mod = (int)(1e9+7);

		for(int size : hm.keySet()){
			int amount = hm.get(size);
			long mult = hm.get(size)*size;
			if(size > 1 && hm.containsKey(1)){
				mult += hm.get(1);
			}

			if(size > 2 && size % 2 == 0){
				if(hm.containsKey(2)){
					mult += hm.get(2)*2;
				}
			}

			for(int div = 3; div <= Math.sqrt(size)+1; div += 2){
				if(div == size) break;
				if(size % div ==0 && hm.containsKey(div)){
					mult += hm.get(div)*div;
					mult %= mod;

					int other = size/div;
					if(other > div && hm.containsKey(other)){
						mult += hm.get(other)*other;
						mult %= mod;
					}

				}
			}

			mult = fastexpo(mult,amount);
			ans *= mult;
			ans %= mod;
		}

		System.out.println(ans);

		qwe.close();
	}

	static long fastexpo(long b, long pow){
		if(pow == 0) return 1l;

		long temp = fastexpo(b,pow/2);
		temp *= temp;
		temp %= mod;
		if(pow % 2 == 1) temp *= b;

		return temp%mod;

	}

}

/*package whatever //do not write package name here */

import java.io.*;

public class Main {
    final static double mod = 1e9 + 7;
	public static void main (String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		String[] input = bf.readLine().split(" ");
		long p = Long.parseLong(input[0]);
		long k = Long.parseLong(input[1]);
		long order = 1;
		long temp = k;

		if (k == 0)
		    System.out.println((int)Math.pow(p, p - 1));
		else {
    	    while (temp != 1) {
    	        temp = (k * temp) % p;
    	        order++;
    	    }

    	    if (k == 1)
		        System.out.println((((int)Math.pow(p, (p - 1)/order)) % (int) mod)*p);
		    else
		        System.out.println((((int)Math.pow(p, (p - 1)/order)) % (int) mod));
		}
	}
}

import java.util.*;
import java.io.*;

public class Main {

    public static long phi(long n) {
       long result = n;
       for (int p = 2; p * p <= n; ++p) {
           if (n % p == 0) {
               while (n % p == 0)
                   n /= p;
               result -= result/p;
           }
       }
       if (n > 1)
           result -= result/n;

       return result;
   }

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String[] input = bf.readLine().split(" ");
        long p = Long.parseLong(input[0]);
        long k = Long.parseLong(input[1]);

        System.out.println((int) Math.pow(p,phi(k)));
    }
}

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class Main {

    static int[] next;
    static boolean[] visit;

    public static void main(String[] args) throws Exception {
        Reader in = new Reader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));

        int p, k;
        p = in.nextInt();
        k = in.nextInt();

        next = new int[p];
        visit = new boolean[p];
        Map<Integer, Integer> count = new HashMap<>();
        for (int i = 0; i < p; i++) {
            next[i] = (int) ((((long) k) * ((long) i)) % p);
        }

        int n = dfs(1, 1);

        long mod = 1000000007;

        int time = (p - 1) / n;
        long ans = 1;
        for (int i = 0; i < time; i++) {
            ans = (ans * p) % mod;
        }

        out.println(ans);

        out.flush();
        in.close();
        out.close();
    }

    private static int dfs(int now, int deep) {
        visit[now] = true;
        int x = next[now];
        if (visit[x]) {
            return deep;
        } else {
            return dfs(x, deep + 1);
        }
    }

    static class Reader {
        BufferedReader reader;
        StringTokenizer st;

        Reader(InputStreamReader stream) {
            reader = new BufferedReader(stream);
            st = null;
        }

        void close() throws IOException {
            reader.close();
        }

        String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        String nextLine() throws IOException {
            return reader.readLine();
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class BalabizooFTW
{

	static class DSU
	{
		int rank[];
		int parent[];
		int N;
		int sets;
		int setsize[];

		public DSU(int N)
		{
			this.N = N;
			sets = N;
			parent = new int[N];
			rank = new int[N];
			setsize = new int[N];
			for(int i=0;i<N;i++){ parent[i] = i; setsize[i] = 1; }

		}

		public void union(int x,int y)
		{
			if(isSameSet(x,y)) return;
			sets--;
			int xp = getParent(x);
			int yp = getParent(y);
			if(rank[xp]>rank[yp]){ parent[yp] = xp; setsize[xp]+=setsize[yp];}
			else{
				if(rank[xp]==rank[yp]){
					rank[yp]++;
					parent[xp] = yp;
					setsize[yp]+=setsize[xp];
				}
				else
				{ parent[xp] =yp; setsize[yp] += setsize[xp]; }
			}

		}

		public int getParent(int x){
			if(x==parent[x]) return x;
			return parent[x] = getParent(parent[x]);
		}

		public boolean isSameSet(int x,int y){
			return getParent(x)==getParent(y);
		}

		public int numDisjointSets(){
			return sets;
		}
		public int getSetSize(int x){
			return setsize[getParent(x)];
		}

	}

	static  long  modPow(long a, long b, long m)
	{
		long  tempo;
		if (b ==0 ){
			tempo =  1;  //EXIT condition
		}//if
		else  if (b == 1) tempo = a;
		else { long temp = modPow(a,b/2,m);
		if (b%2 == 0)
			tempo = (temp*temp)%m;
		else
			tempo = ((temp*temp)%m)*a%m;
		}
		return tempo;
	}

	static long p,k;
	public static void main(String[]args)throws Throwable
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer	st = new StringTokenizer(br.readLine());
		p = new Long(st.nextToken());
		k = new Long(st.nextToken());
		DSU dsu = new DSU((int)p);
		for(int i = 0 ; i < p ; ++i)
		{
			dsu.union(i, (int)((k%p*i%p) % p));
		}
		System.out.println(modPow(p,dsu.numDisjointSets() - 1,1000*1000*1000 +7));

	}

}

import java.util.*;

public class D {

    public static void main(String[] args) {
    	Scanner s = new Scanner(System.in);
    	int p, k;
    	p = s.nextInt();
    	k = s.nextInt();
    	if(k == 0) {
    		long ans = 1;
    		for(int i=1; i<p; i++)
    			ans = (ans*p)%1000000007;
    		System.out.println(ans);
    		System.exit(0);
    	}
    	boolean[] graph = new boolean[p];
    	long ans = 1;
    	for(int i=0; i<p; i++) {
    		if(!graph[i]) {
    			long tmp = i;
    			int rot = 0;
    			do {
    				graph[(int)tmp] = true;
    				tmp = (tmp*k)%p;
    				rot++;
    			} while(tmp != i);
    			if(rot != 1)
	    			ans = (ans*p)%1000000007;
	    		else ans = (((ans*p)%1000000007)*p)%1000000007;
    		}
    	}
    	System.out.println(ans);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.math.BigInteger;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author ilyakor
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        static final long mod = 1000 * 1000 * 1000 + 7;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int p = in.nextInt();
            int k = in.nextInt();
            if (k == 0) {
                long res = IntegerUtils.pow(p, p - 1, mod);
                out.printLine(res);
                return;
            }
            int cnt = 0;
            long cur = 1;
            do {
                ++cnt;
                cur = (cur * (long) k) % p;
            } while (cur != 1);
            Assert.assertTrue((p - 1) % cnt == 0);
            long r = (p - 1) / cnt;
            long res = IntegerUtils.pow(p, r, mod);
            out.printLine(res);
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

        public void close() {
            writer.close();
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buffer = new byte[10000];
        private int cur;
        private int count;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public static boolean isSpace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public int read() {
            if (count == -1) {
                throw new InputMismatchException();
            }
            try {
                if (cur >= count) {
                    cur = 0;
                    count = stream.read(buffer);
                    if (count <= 0)
                        return -1;
                }
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            return buffer[cur++];
        }

        public int readSkipSpace() {
            int c;
            do {
                c = read();
            } while (isSpace(c));
            return c;
        }

        public int nextInt() {
            int sgn = 1;
            int c = readSkipSpace();
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = read();
            } while (!isSpace(c));
            res *= sgn;
            return res;
        }

    }

    static class Assert {
        public static void assertTrue(boolean flag) {
//        if (!flag)
//        while (true);
            if (!flag)
                throw new AssertionError();
        }

    }

    static class IntegerUtils {
        public static long pow(long x, long y, long mod) {
            x %= mod;
            long res = 1;
            while (y > 0) {
                if (y % 2 == 1) {
                    --y;
                    res = BigInteger.valueOf(res).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
                } else {
                    y /= 2;
                    x = BigInteger.valueOf(x).multiply(BigInteger.valueOf(x)).mod(BigInteger.valueOf(mod)).longValue();
                }
            }
            return res % mod;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class D {
	final long MOD = (long)(1e9+7);
	long p,k;
	void readInput() throws NumberFormatException, IOException{
		//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		Scanner sc = new Scanner(System.in);
		p = sc.nextLong();
		k = sc.nextLong();
	}

	public static long powmod(long a, long x, long n){
		long res = 1;
		a = a % n;
		while(x>0){
			if ( x % 2 == 1)
				res = (res*a) %n;
			a = (a*a) %n;
			x = x >> 1;
		}
		return res;
	}

	void solve(){
		long ssol = 0;
		if (k<=1)
			ssol = powmod(p, p, MOD);
		else  if (k==p-1){
			ssol = powmod(p, (p-1)/2, MOD);
		}
		else
			ssol = p;
		System.out.println(ssol);
	}

	public static void main(String[] args) throws NumberFormatException, IOException {
		D a = new D();
		a.readInput();
		a.solve();
	}

}

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 * @author pttrung
 */
public class B_Round_334_Div1 {

    public static long MOD = 1000000007;

    public static void main(String[] args) throws FileNotFoundException {
        // PrintWriter out = new PrintWriter(new FileOutputStream(new File(
        // "output.txt")));
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        int p = in.nextInt();
        int k = in.nextInt();
        long[]l = new long[p + 1];
        int[]check = new int[p];
        check[0] = 1;
        l[1]++;
        for(int i = 1; i < p; i++){
        	if(check[i] == 0){
        		int v = i;
        		int c = 0;
        		do{
        			check[v] = -1;
        			c++;
        			v = (k*v) % p;
        		}while(check[v] == 0);
        		check[i] = c;
        		l[c]++;
        	}
        }
       // System.out.println(Arrays.toString(l) + " " + Arrays.toString(check));
        long[]pre = new long[p + 1];
        pre[0] = 1;
        for(int i = 1; i < pre.length; i++){
        	pre[i] = (long)i * pre[i -1];
        	pre[i] %= MOD;
        }
        long result = 1;
        for(int i = 0 ; i < p; i++){
        	if(check[i] != -1){
        		long total = 0;
        		for(int j = 1; j* j <= check[i]; j++){
        		    if(check[i] % j == 0){
        		    	int  o = check[i] / j;
        		    	total += (l[j]*j) % MOD;
        		    	total %= MOD;
        		    	if(o != j){
        		    		total += (l[o]*o) % MOD;
            		    	total %= MOD;
        		    	}
        		    }
        		}
        		//System.out.println(total + " " + i);
        		result *= total;
        		result %= MOD;
        	}
        }
        out.println(result);
       // out.println(cal(0,new int[p], k));
        out.close();
    }

    public static int cal(int index, int[]data, int k){
    	if(index == data.length){
    		int p = data.length;
    		boolean ok = true;
    		for(int i = 0; i < p; i++){
    			if((k * data[i] ) % p != data[(i *k) % p]){
    				ok = false;
    				break;
    			}
    		}
    		if(ok){
    			System.out.println(Arrays.toString(data));
    		    return 1;
    		}
    		return 0;
    	}
    	int result = 0;
    	for(int i = 0; i< data.length; i++){
    		data[index] = i;
    		result += cal(index + 1, data, k);
    	}
    	return result;
    }

    public static int[] KMP(String val) {
        int i = 0;
        int j = -1;
        int[] result = new int[val.length() + 1];
        result[0] = -1;
        while (i < val.length()) {
            while (j >= 0 && val.charAt(j) != val.charAt(i)) {
                j = result[j];
            }
            j++;
            i++;
            result[i] = j;
        }
        return result;

    }

    public static boolean nextPer(int[] data) {
        int i = data.length - 1;
        while (i > 0 && data[i] < data[i - 1]) {
            i--;
        }
        if (i == 0) {
            return false;
        }
        int j = data.length - 1;
        while (data[j] < data[i - 1]) {
            j--;
        }
        int temp = data[i - 1];
        data[i - 1] = data[j];
        data[j] = temp;
        Arrays.sort(data, i, data.length);
        return true;
    }

    public static int digit(long n) {
        int result = 0;
        while (n > 0) {
            n /= 10;
            result++;
        }
        return result;
    }

    public static double dist(long a, long b, long x, long y) {
        double val = (b - a) * (b - a) + (x - y) * (x - y);
        val = Math.sqrt(val);
        double other = x * x + a * a;
        other = Math.sqrt(other);
        return val + other;

    }

    public static class Point implements Comparable<Point> {

        int x, y;

        public Point(int start, int end) {
            this.x = start;
            this.y = end;
        }

        @Override
        public int hashCode() {
            int hash = 5;
            hash = 47 * hash + this.x;
            hash = 47 * hash + this.y;
            return hash;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Point other = (Point) obj;
            if (this.x != other.x) {
                return false;
            }
            if (this.y != other.y) {
                return false;
            }
            return true;
        }

        @Override
        public int compareTo(Point o) {
            return x - o.x;
        }
    }

    public static class FT {

        long[] data;

        FT(int n) {
            data = new long[n];
        }

        public void update(int index, long value) {
            while (index < data.length) {
                data[index] += value;
                index += (index & (-index));
            }
        }

        public long get(int index) {
            long result = 0;
            while (index > 0) {
                result += data[index];
                index -= (index & (-index));
            }
            return result;

        }
    }

    public static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static long pow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b == 1) {
            return a;
        }
        long val = pow(a, b / 2);
        if (b % 2 == 0) {
            return val * val % MOD;
        } else {
            return val * (val * a % MOD) % MOD;

        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            //  br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
        }

        public String next() {

            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
            return st.nextToken();
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public String nextLine() {
            st = null;
            try {
                return br.readLine();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }

        public boolean endLine() {
            try {
                String next = br.readLine();
                while (next != null && next.trim().isEmpty()) {
                    next = br.readLine();
                }
                if (next == null) {
                    return true;
                }
                st = new StringTokenizer(next);
                return st.hasMoreTokens();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }
}

import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by chavit on 01.12.2015.
 */
public class B {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        long res = 1, mod = (long) (1e+9 + 7);
        if (k == 0) {
            for (int i = 1; i < n; i++) {
                res = (res * n) % mod;
            }
            System.out.println(res);
            return;
        }
        int[] multiplier = new int[n];
        for (int i = 1; i < n; i++) {
            int pos = i;
            if (multiplier[pos] != 0) {
                continue;
            }
            res = (res * n) % mod;
            while (multiplier[pos] != 1) {
                multiplier[pos] = 1;
                pos = (int) (((long) pos * (long) k) % (long) n);
            }
        }
        System.out.println(res);
    }
}

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
	  br = new BufferedReader(new FileReader("input.txt"));
	  pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
	  br = new BufferedReader(new InputStreamReader(System.in));
	  pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
 */

public class Main {
	private static BufferedReader br;
	private static StringTokenizer st;
	private static PrintWriter pw;

	public static void main(String[] args) throws Exception {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		//int qq = 1;
		int qq = Integer.MAX_VALUE;
		//int qq = readInt();
		for(int casenum = 1; casenum <= qq; casenum++)	{
			int n = readInt();
			int k = readInt();
			long[] fact = new long[n+1];
			boolean[] seen = new boolean[n];
			int[] numCycles = new int[n+1];
			long ret = 1;
			final int MOD = 1000000007;
			fact[0] = 1;
			for(int i = 1; i <= n; i++) {
				fact[i] = fact[i-1] * i;
				fact[i] %= MOD;
			}
			for(int i = 0; i < n; i++) {
				if(seen[i]) continue;
				int len = 0;
				long curr = i;
				while(!seen[(int)curr]) {
					seen[(int)curr] = true;
					len++;
					curr *= k;
					curr %= n;
				}
				numCycles[len]++;
			}
			for(int i = 0; i <= n; i++) {
				if(numCycles[i] == 0) continue;
				long amtForOne = 0;
				for(int a = 1; a * a <= i; a++) {
					if(i%a == 0) {
						amtForOne += numCycles[a] * 1L * a;
						amtForOne %= MOD;
						if(a * a != i) {
							amtForOne += numCycles[(i/a)] * 1L * (i/a);
							amtForOne %= MOD;
						}
					}
				}
				for(int a = 0; a < numCycles[i]; a++) {
					ret *= amtForOne;
					ret %= MOD;
				}
			}
			pw.println(ret);
		}
		exitImmediately();
	}

	private static void exitImmediately() {
		pw.close();
		System.exit(0);
	}

	private static long readLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	private static double readDouble() throws IOException {
		return Double.parseDouble(nextToken());
	}

	private static int readInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	private static String nextLine() throws IOException  {
		if(!br.ready()) {
			exitImmediately();
		}
		st = null;
		return br.readLine();
	}

	private static String nextToken() throws IOException  {
		while(st == null || !st.hasMoreTokens())  {
			if(!br.ready()) {
				exitImmediately();
			}
			st = new StringTokenizer(br.readLine().trim());
		}
		return st.nextToken();
	}
}

import java.util.*;

public class Modular {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        long p = scan.nextInt();
        long k = scan.nextInt();

        if(k > 1 && (k < p - 1)) {
            System.out.println(1);
            return;
        }

        long half = (p - 1) / 2;
        long res = 1;
        long mod = (long)Math.pow(10, 9) + 7;

        for(long i = 1; i <= half; i++) {
            res = (res * p) % mod;
        }

        if(k == p - 1) {
            System.out.println(res);
            return;
        }

        for(long i = half+1; i <= p-1; i++) {
            res = (res * p) % mod;
        }

        if(k == 0) {
            System.out.println(res);
            return;
        }

        res = (res * p) % mod;
        System.out.println(res);
    }
}

import java.math.BigInteger;
import java.util.Scanner;

public class D {

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		String[] firstLine = s.nextLine().split(" ");

		boolean[] done = new boolean[Integer.parseInt(firstLine[0])];
		int K = Integer.parseInt(firstLine[1]);

		BigInteger ways = new BigInteger("1");

		if (K != 0) {

		int[] cycles = new int[done.length];

		for (int i = 1; i < done.length; i++) {

			if (!done[i]) {

				done[i] = true;
				long cycleLength = 1;
				long start = (i * (long) K) % done.length;

				while (start != i) {

					done[(int) start] = true;
					start *= K;
					start %= done.length;
					cycleLength++;

				}

				cycles[(int) cycleLength]++;

			}

		}

		for (int i = 0; i < cycles.length; i++) {

			if (cycles[i] != 0) {

				ways = ways.multiply(new BigInteger(String.valueOf(cycles[i] * i + 1)).modPow(new BigInteger(String.valueOf(cycles[i])), new BigInteger("1000000007")));

			}

		}

		}else{

			int p = done.length;
			ways = new BigInteger(String.valueOf(p));
			ways = ways.modPow(new BigInteger(String.valueOf(p - 1)), new BigInteger("1000000007"));

		}

		System.out.println(ways);

		s.close();
		System.exit(0);

	}

}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class Main {
    public static void main(String[] args) {
//     Test.testing();
        ConsoleIO io = new ConsoleIO();
        new Main(io).solve();
        io.flush();
    }
    ConsoleIO io;
    Main(ConsoleIO io) {
        this.io = io;
    }

    ArrayList<ArrayList<Integer>> gr1;
    ArrayList<ArrayList<Integer>> gr2;
    boolean[] visit;
    //

    public void solve() {
        int[] l = io.readIntArray();
        long p = l[0], k = l[1];
        long res = 1;
        long mod = 1000_000_007;
        visit = new boolean[(int) p];
        for (int i = 1; i < p; i++) {
            int h = i;
            boolean need = false;
            while (!visit[h]) {
                need = true;
                visit[h] = true;
                h = (int) (k * h % p);
            }
            if(need) res = (res * p) % mod;
        }
        io.writeLine(res + "");
    }

}

class ConsoleIO {
    BufferedReader br;
    PrintWriter out;
    public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
    public void flush(){this.out.close();}
    public void writeLine(String s) {this.out.println(s);}
    public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
    public void writeWord(String s){
        this.out.print(s);
    }
    public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
    public long readLong() {
        return Long.parseLong(this.readLine());
    }
    public int readInt() {
        return Integer.parseInt(this.readLine().trim());
    }
    public long[] readLongArray() {
        String[]n=this.readLine().trim().split(" ");long[]r=new long[n.length];
        for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
        return r;
    }
    public int[] readIntArray() {
        String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
        for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
        return r;
    }
}

import java.io.*;
import java.util.*;

public class Main {
    static int inf = (int) 1e9 + 7;

    public static void main(String[] args) throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        pw = new PrintWriter(System.out);
        int p = nextInt();
        int k = nextInt();
        long ans = 1;
        boolean used[] = new boolean[p];
        for(int i = 1;i < p;i++) {
            int v = i;
            if (!used[i]) {
                while (!used[v]) {
                    used[v] = true;
                    v = (v * k) % p;
                }
                ans = (ans * p) % inf;
            }
        }

        pw.println(ans);
        pw.close();
    }

    static BufferedReader br;
    static StringTokenizer st = new StringTokenizer("");
    static PrintWriter pw;

    static String next() throws IOException {
        while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}

import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;

import java.util.*;
import java.io.*;

@SuppressWarnings("unused")
public class Main {
    public static void main(String[] args) throws IOException {
        new Main().run();
    }

    BufferedReader in;
    PrintWriter out;
    StringTokenizer st = new StringTokenizer("");

    private void run() throws IOException {
        if (new File("input.txt").exists())
            in = new BufferedReader(new FileReader("input.txt"));
        else
            in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        solve();
        in.close();
        out.close();
    }

    long MOD = 1;

    long AMOD = 1000 * 1000 * 1000 + 7L;

    private void solve() throws IOException {

        int p = nextInt();
        MOD = p;
        int k = nextInt();
        boolean u[] = new boolean[p];
        int cnt = 0;
        for (int i = 1; i < p; i++) {
            if (!u[i]) {
                cnt++;
                int cur = i;
//              System.err.println("i " + i);
                while (true) {
                    if (u[cur])
                        break;
                    u[cur] = true;
                    long x = cur * k;
                    x %= p;
                    cur = (int)x;
//                  System.err.println("cur " + cur);
                }
            }
        }

//      System.err.println(cnt);

        long ans = 0;
        if (k == 0) {
            ans = apow(p, p - 1);
        }
        else {

            int y = (p - 1) / cnt;
//          System.err.println(y);
            long fac[] = new long[cnt + 1];
            fac[0] = 1L;

            for (int i = 0; i < cnt; i++) {
                fac[i + 1] = fac[i] * (i + 1L);
                fac[i + 1] %= AMOD;
            }

            for (int i = 0; i <= cnt; i++) {
                long cans = fac[cnt];
//              cans *= fac[cnt];
//              cans %= AMOD;
                cans *= apow(fac[i], AMOD - 2);
                cans %= AMOD;
//              cans *= apow(fac[i], AMOD - 2);
//              cans %= AMOD;
                cans *= apow(fac[cnt - i], AMOD - 2);
                cans %= AMOD;
//              cans *= apow(fac[cnt - i], AMOD - 2);
//              cans %= AMOD;

//              System.err.println(cans);
                cans *= apow(y, (cnt - i));
                cans %= AMOD;
                cans *= apow(cnt, (cnt - i));
                cans %= AMOD;
//              System.err.println(cans);
                ans += cans;
                ans %= AMOD;
            }
//          System.err.println(fac[2]);
//          System.err.println(apow(2, 10));

        }

        out.println(ans);

    }

    long pow(long a, long b) {
        if (b == 0)
            return 1L;
        long x = pow(a, b / 2);
        x = (x * x % MOD);
        if (b % 2 == 1) {
            x = (x * a % MOD);
        }
        return x;
    }

    long apow(long a, long b) {
        if (b == 0)
            return 1L;
        long x = apow(a, b / 2);
        x = (x * x % AMOD);
        if (b % 2 == 1) {
            x = (x * a % AMOD);
        }
        return x;
    }

    void chk(boolean b) {
        if (b)
            return;
        System.out.println(new Error().getStackTrace()[1]);
        exit(999);
    }
    void deb(String fmt, Object... args) {
        System.out.printf(Locale.US, fmt + "%n", args);
    }
    String nextToken() throws IOException {
        while (!st.hasMoreTokens())
            st = new StringTokenizer(in.readLine());
        return st.nextToken();
    }
    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
    String nextLine() throws IOException {
        st = new StringTokenizer("");
        return in.readLine();
    }
    boolean EOF() throws IOException {
        while (!st.hasMoreTokens()) {
            String s = in.readLine();
            if (s == null)
                return true;
            st = new StringTokenizer(s);
        }
        return false;
    }
}