#include <bits/stdc++.h>
using namespace std;
//十进制转 N 进制
string Base(int n, int M){
string s = "";
int x;
char c;
while (n != 0){
x = n % M;//x:0,1
c = x + '0';//结果逆序连接为字符串
s = c + s;
n = n / M;
}
if (s == ""){
s = "0";
}
return s;
}
//回文数
bool huiwen(string s){
bool flag = 1;
for (int i = 0; i < s.size()/2; i++){
if (s[i] != s[s.size()-i-1]){
flag = 0;
break;
}
}
return flag;
}
int main(){
int N, M, k = 0;
string p = "";
cin >> N >> M;
for (int i = 1; i <= N; i++){
if (huiwen(Base(i * i, M))) k++;
}
cout << k;
}