#include using namespace std; using ll = long long; int modpow(int a, ll ex, int B) { int res = 1; while (ex) { if (ex & 1) res = res * a % B; a = a * a % B; ex >>= 1; } return res; } int main(){ ios::sync_with_stdio(false); cin.tie(0); ll N; int B; cin >> N >> B; vector tb(B), tb2(B); for(int i = 0; i < B; i++){ tb2[i] = modpow(i, N, B); tb[tb2[i]]++; } ll ans = 0; for(int i = 0; i < B; i++){ for(int j = 0; j < B; j++){ int v = tb2[i] + tb2[j]; ans += tb[v >= B ? v - B : v]; } } cout << ans << '\n'; }