1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <cstdio> #include <cmath> using namespace std; const int N = 1e6 + 10, M = 1e3 + 10; int n, m, q; int cnt, p[N], v[N], div[N][3], g[M][M]; void init() { v[1] = 1; for (int i = 2; i < N; i++) { if (!v[i]) { p[++cnt] = i; v[i] = i; } for (int j = 1; j <= cnt && i * p[j] < N; j++) { v[i * p[j]] = p[j]; if (i % p[j]) break; } } div[1][0] = div[1][1] = div[1][2] = 1; for (int i = 1; i < N; i++) { for (int j = 0; j < 3; j++) div[i][j] = div[i / v[i]][j]; for (int j = 0; j < 3; j++) if (div[i][j] * v[i] <= m) { div[i][j] *= v[i]; break; } } for (int i = 1; i <= m; i++) for (int j = 1; j <= i; j++) g[i][j] = g[j][i] = g[j][i % j]; } int main() { scanf("%d%d", &n, &q); m = sqrt(n); init(); for (int a, b; q; q--) { scanf("%d%d", &a, &b); int res = 1, d; for (int i = 0; i < 3; i++) { if (div[a][i] <= m) d = g[div[a][i]][b % div[a][i]]; else d = b % div[a][i] == 0 ? div[a][i] : 1; res *= d; b /= d; } printf("%d\n", res); } return 0; }
|