#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <complex>
#include <queue>
#include <stack>
#include <cmath>
#include <cassert>
#include <tuple>
using namespace std;
typedef long long LL;
typedef complex<double> CMP;

static const unsigned MODVAL = 1000000007;
struct mint
{
	unsigned val;
	mint():val(0){}
	mint(int      x):val(x%MODVAL) {}
	mint(unsigned x):val(x%MODVAL) {}
	mint(LL       x):val(x%MODVAL) {}
};
mint& operator+=(mint& x, mint y) { return x = x.val+y.val; }
mint& operator-=(mint& x, mint y) { return x = x.val-y.val+MODVAL; }
mint& operator*=(mint& x, mint y) { return x = LL(x.val)*y.val; }
mint operator+(mint x, mint y) { return x+=y; }
mint operator-(mint x, mint y) { return x-=y; }
mint operator*(mint x, mint y) { return x*=y; }

mint POW(mint x, LL e) { mint v=1; for(;e;x*=x,e>>=1) if(e&1) v*=x; return v; }

class PairsOfStrings { public:
	int getNumber(int n, int k)
	{
		set<int> ds;
		for(int d=1; d*d<=n; ++d)
			if(n%d == 0) {
				ds.insert(d);
				ds.insert(n/d);
			}

		memo.clear();

		mint total = 0;
		for(int d: ds)
			total += count_unit(ds, d, k) * d;
		return total.val;
	}

	map<int, mint> memo;
	mint count_unit(const set<int>& ds, int d, int k)
	{
		if(memo.count(d))
			return memo[d];

		mint v = POW(k, d);
		for(int x: ds) {
			if(x>=d)
				break;
			if(d%x==0)
				v -= count_unit(ds, x, k);
		}
		return memo[d] = v;
	}
};

// BEGIN CUT HERE
#include <ctime>
double start_time; string timer()
 { ostringstream os; os << " (" << int((clock()-start_time)/CLOCKS_PER_SEC*1000) << " msec)"; return os.str(); }
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v)
 { os << "{ ";
   for(typename vector<T>::const_iterator it=v.begin(); it!=v.end(); ++it)
   os << '\"' << *it << '\"' << (it+1==v.end() ? "" : ", "); os << " }"; return os; }
void verify_case(const int& Expected, const int& Received) {
 bool ok = (Expected == Received);
 if(ok) cerr << "PASSED" << timer() << endl;  else { cerr << "FAILED" << timer() << endl;
 cerr << "\to: \"" << Expected << '\"' << endl << "\tx: \"" << Received << '\"' << endl; } }
#define CASE(N) {cerr << "Test Case #" << N << "..." << flush; start_time=clock();
#define END	 verify_case(_, PairsOfStrings().getNumber(n, k));}
int main(){

CASE(0)
	int n = 2; 
	int k = 2; 
	int _ = 6; 
END
CASE(1)
	int n = 3; 
	int k = 2; 
	int _ = 20; 
END
CASE(2)
	int n = 3; 
	int k = 4; 
	int _ = 184; 
END
CASE(3)
	int n = 6; 
	int k = 2; 
	int _ = 348; 
END
CASE(4)
	int n = 100; 
	int k = 26; 
	int _ = 46519912; 
END
CASE(5)
	int n = 100000000; 
	int k = 26; 
	int _ = -1; 
END
/*
CASE(6)
	int n = ; 
	int k = ; 
	int _ = ; 
END
*/
}
// END CUT HERE
