/* Given a long number N(with less than 1000 digits), a divisor(<=1000),
   Find the least number of digits in N that needed to be removed and
   the resulting number is divisible by divisor

   time used: thinking: 3-4hours
              coding:   1-2hours
 */
#include <iostream.h>
#include <string.h>

int divisor;
char inputchar[1024];
int number[1024]; // the input long number,
                  // [0] is the last digit, [1] is the tenth digit and so on
int length;       // length of the long number
int position[1024];     // the weighting of each dight, [i] = (10^i)%divisor
bool map[1024][1024];   // [i][j] is true iff "by removing level digits,
                        // it is possible to form a number with %divisor = j,
                        // but the number use only i digits in the long number,
                        // starting from the least significant digit
int level;              // number of digit removed

void input(){
  cin >> inputchar;
  cin >> divisor >> ws;
  length = strlen( inputchar );
  for( int i=0; i<length; i++ ){
    number[i] = inputchar[length-1-i]-48;  // turn to single digits
  }
  position[0] = 1%divisor;
  for( int i=1; i<length; i++ ){
    position[i] = (position[i-1]*10)%divisor;
  }
//  cout << inputchar << " " << divisor << endl;
}

void do_work(){
  int temp;
  for( int i=0; i<1024; i++ ){
    for( int j=0; j<1024; j++ ){
      map[i][j] = 0;
    }
  }
  map[0][0] = 1;
//  for( int i=0; i<length; i++ ){
//    for( int j=0; j<divisor; j++ ){
//      cout << map[i][j];
//    }
//    cout << endl;
//  }
  for( level = 0; level<=length; level++ ){
    for( int i=1; i<=length-level; i++ ){
      for( int j=0; j<divisor; j++ ){
 if( map[i-1][j] ){
   temp = ( j + number[i+level-1]*position[i-1] )%divisor;
   map[i][temp] = 1;
 }
      }
    }
    if( map[length-level][0] ){
      cout<< level << endl;
      return;
    }
  }
  return;
}

int main(){
  int n;
  cin >> n >> ws;
  for (int i = 0; i < n; ++i) {
    input();
    do_work();
  }
  return 1;
}
