#include <bits/stdc++.h>
using namespace std;
vector<long long> factors(long long n) {
  vector<long long> fac;
  for (long long i = 1; i * i <= n; i++)
    if (n % i == 0) {
      fac.push_back(i);
      fac.push_back(n / i);
    }
  return fac;
}
int main() {
  long long t;
  cin >> t;
  while (t--) {
    long long n, k;
    cin >> n >> k;
    string s;
    cin >> s;
    long long a[26] = {};
    for (long long i = 0; i < n; i++) a[s[i] - 'a']++;
    vector<long long> fac = factors(k);
    long long m = fac.size();
    long long ans = 0;
    for (long long i = 0; i < m; i++) {
      for (long long len = fac[i]; len <= n; len += fac[i]) {
        long long factor = fac[i];
        long long atleast = len / factor;
        long long value = 0;
        for (long long j = 0; j < 26; j++) value += a[j] / atleast;
        if (value >= factor) ans = max(ans, len);
      }
    }
    cout << ans << "\n";
  }
  return 0;
}
