天天看點

HDU 2837 Calculation

Description

Assume that f(0) = 1 and 0^0=1. f(n) = (n%10)^f(n/10) for all n bigger than zero. Please calculate f(n)%m. (2 ≤ n , m ≤ 10^9, x^y means the y th power of x).

Input

The first line contains a single positive integer T. which is the number of test cases. T lines follows.Each case consists of one line containing two positive integers n and m.

Output

One integer indicating the value of f(n)%m.

Sample Input

2

24 20

25 20

Sample Output

16

5

#include<set>
#include<map>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
#define loop(i,j,k) for (int i = j;i != -1; i = k[i])
#define lson x << 1, l, mid
#define rson x << 1 | 1, mid + 1, r
#define ff first
#define ss second
#define mp(i,j) make_pair(i,j)
#define pb push_back
#define pii pair<int,LL>
#define inone(x) scanf("%d", &x);
#define intwo(x,y) scanf("%d%d", &x, &y);
using namespace std;
typedef long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-4;
const int INF = 0x7FFFFFFF;
//const int mod = 1e9 + 7;
const int N = 1e5 + 10;
int T, n, mod[N], a[N];
char s[N];

int phi(int x)
{
  int res = 1;
  for (int i = 2; i*i <= x; i++)
  {
    if (x%i) continue;
    res *= i - 1;
    for (x /= i; !(x%i); res *= i, x /= i);
  }
  return res * max(x - 1, 1);
}

LL get(LL x, LL y, LL z)
{
  LL res = 1, p = 1;
  if (x > 1)
  {
    rep(i, 1, y)
    {
      p *= x;
      if (p >= z) break;
    }
  }
  else p = x ? 1 : y ? 0 : 1;
  for (; y; y >>= 1)
  {
    if (y & 1) res = res * x % z;
    x = x * x % z;
  }
  if (p >= z) return res % z + z;
  return res;
}

int f(int x, int m)
{
  if (x == 1) return a[x] >= m ? a[x] % m + m : a[x];
  return get(a[x], f(x - 1, mod[x - 1]), m);
}

int main()
{
  inone(T);
  while (T--)
  {
    scanf("%s", s + 1); n = strlen(s + 1);
    inone(mod[n]);
    per(i, n - 1, 1) mod[i] = phi(mod[i + 1]);
    rep(i, 1, n) a[i] = s[i] - '0';
    printf("%d\n", f(n, mod[n]) % mod[n]);
  }
  return 0;
}