//#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = max( sr - 100, 0 );
            int g2 = sr + 100;

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[101][101];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            for( int k = min( sr - 500, 0 ) ; k <= sr + 500 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


#include <ext/pb_ds/assoc_container.hpp>
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <algorithm>
#include <utility>
#include <cmath>
#include <iomanip>
#include <stack>
#include <deque>
#include <queue>
#include <cstdio>
#include <unordered_map>
#include <unordered_set>
#include <numeric>
#include <cassert>
#include <ext/rope>
#include <random>
#include <ctime>
#include <chrono>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <bitset>

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> (istream & in, vec< T > & a)
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << (ostream & out, vec< T > & a)
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template <class T, class U>
ostream& operator << (ostream & out, pair< T, U > &a)
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a)
{
    in >> a.f >> a.s;
    return in;
}

/*
const int MAX_MEM = 5e8;
char MEM[MAX_MEM];
int MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
#define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
#define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
mt19937 rnd(345345);
#else
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max(int a, int b)
{
    if(a > b)
    {
        return a;
    }
    return b;
}

int min(int a, int b)
{
    if(a < b)
    {
        return a;
    }
    return b;
}

void start()
{
    freopen("prizes.in", "r", stdin);
    freopen("prizes.out", "w", stdout);
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    vec<vec<int>> A(n, vec<int> (m));
    cin >> A;

    // 1 -> 0
    // 2 -> (a + b) / 2
    // 4 -> {a, b, c, d} -> b/c

    int ans = 0;

    FOR(i, (n + 1) / 2)
    {
        FOR(j, (m + 1) / 2)
        {
            int a = A[i][j];
            int b = A[n - i - 1][j];
            int c = A[i][m - j - 1];
            int d = A[n - i - 1][m - j - 1];

            if(n - i - 1 == i and m - j - 1 == j) continue;

            if(m - j - 1 == j)
            {
                ans += abs(a - b);
                continue;
            }

            if(n - i - 1 == i)
            {
                ans += abs(a - c);
                continue;
            }

            vec<int> str;

            str.pb(a);
            str.pb(b);
            str.pb(c);
            str.pb(d);

            sort(all(str));

            int mn = INF;

            mn = min(mn, abs(a - str[1]) + abs(b - str[1]) + abs(c - str[1]) + abs(d - str[1]));
            mn = min(mn, abs(a - str[2]) + abs(b - str[2]) + abs(c - str[2]) + abs(d - str[2]));

            ans += mn;
        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


//#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = max( sr - 2000, 0 );
            int g2 = sr + 2000;

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


//#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = min( sr, 0 );
            int g2 = sr;

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


//#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = min( sr - 5, 0 );
            int g2 = sr + 5;

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            for( int k = min( sr - 100, 0 ) ; k <= sr + 100 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


//#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = max( sr - 5000, 0 );
            int g2 = sr + 5000;

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = min( sr - 5, 0 );
            int g2 = min( sr - 5, 0 );

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


//#pragma GCC optimize("Ofast,fast-math,unroll-loops")

#ifdef GIG
    #include <iostream>
    #include <vector>
    #include <string>
    #include <set>
    #include <map>
    #include <algorithm>
    #include <utility>
    #include <cmath>
    #include <iomanip>
    #include <stack>
    #include <deque>
    #include <queue>
    #include <cstdio>
    #include <unordered_map>
    #include <unordered_set>
    #include <numeric>
    #include <cassert>
    #include <ext/rope>
    #include <random>
    #include <ctime>
    #include <chrono>
    #include <cassert>
    #include <stdio.h>
    #include <stdlib.h>
    #include <windows.h>
    #include <bitset>
#else
    #include<bits/stdc++.h>
#endif

#define int long long
#define f first
#define s second
#define sz(x) (int)(x.size())
#define pb push_back
#define vec vector
#define all(x) (x).begin(), (x).end()
#define ld long double
#define rall(x) (x).rbegin(), (x).rend()
#define pii pair< int, int >
#define psi pair< string, int >
#define pss pair< string, string >
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound
#define rz resize
#define ins insert
#define endl "\n"
#define FOR( i, n ) for( int i = 0 ; i < (n) ; i++ )
#define INF 1e18
#define inf 1e12
#define sum( a ) accumulate( all( a ), (int)0 )
#define rep( i, a, b ) for( int i = a ; i < b ; i++ )

using namespace std;
using namespace __gnu_cxx;

template <class T>
istream& operator >> ( istream & in, vec< T > & a )
{
    for ( auto & i : a )
        in >> i;
    return in;
}

template <class T>
ostream& operator << ( ostream & out, vec< T > & a )
{
    for ( auto & i : a )
        out << i << ' ';
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        in >> i.f >> i.s;
    return in;
}

template <class T, class U>
ostream& operator << ( ostream & out, vec< pair < T, U > > & a )
{
    for ( auto & i : a )
        out << i.f << ' ' << i.s << endl;
    return out;
}

template <class T, class U>
ostream& operator << ( ostream & out, pair< T, U > &a )
{
    out << a.f << ' ' << a.s << endl;
    return out;
}

template < class T, class U >
istream& operator >> (istream & in, pair< T, U > &a )
{
    in >> a.f >> a.s;
    return in;
}

/*
const ll MAX_MEM = 5e8;
char MEM[MAX_MEM];
ll MEM_POS = 0;
void* operator new(size_t x)
{
    auto ret = MEM + MEM_POS;
    MEM_POS += x;
    assert(MEM_POS < MAX_MEM);
    return ret;
}
void operator delete(void*)
{}
*/

#ifdef FelixDzerzhinsky
    #define dbg(x) cout << (#x) << "\t" << (x) << endl
#else
    #define dbg(x) 238
#endif

#ifdef FelixDzerzhinsky
    mt19937 rnd(345345);
#else
    mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
#endif

int max( int a, int b )
{
    if( a > b )
    {
        return a;
    }
    return b;
}

int min( int a, int b )
{
    if( a < b )
    {
        return a;
    }
    return b;
}

void start()
{
    freopen( "prizes.in", "r", stdin );
    freopen( "prizes.out", "w", stdout );
}

void Ios()
{
    ios_base::sync_with_stdio( 0 );
    cin.tie( 0 );
    cout.tie( 0 );
}

void solve()
{
    int n, m;
    cin >> n >> m;

    int a[n][m];

    int ans = 0;

    FOR( i, n )
    {
        FOR( j, m )
        {
            cin >> a[i][j];
        }
    }

    int s1 = (n + 1) / 2;
    int s2 = (m + 1) / 2;

    FOR( i, s1 )
    {
        FOR( j, s2 )
        {
            int i1 = n - i - 1;
            int j1 = m - j - 1;

            int mn = INF;

            int sr = ( a[i1][j1] + a[i][j1] + a[i1][j] + a[i][j] ) / 4;

            int g1 = max( sr - 500, 0 );
            int g2 = sr + 500;

            for( int k = g1 ; k <= g2 ; k++ )
            {
                int cur = 0;
                if( i1 == i and j == j1 )
                {
                        // 0
                }
                else if( i1 == i )
                {
                    cur += abs(a[i1][j1] - k) + abs(a[i1][j] - k);
                }
                else if( j1 == j )
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k);
                }
                else
                {
                    cur += abs(a[i][j] - k) + abs(a[i1][j] - k) + abs(a[i][j1] - k) + abs(a[i1][j1] - k);
                }

                mn = min( mn, cur );
            }

            ans += mn;

        }
    }

    cout << ans << endl;
}

signed main()
{
    //start();
    Ios();

    int q = 1;
    cin >> q;

    while( q-- )
    {
        solve();
    }
}


fun main() {
    var t = readLine()!!.toLong()
    while (t--){
    	var n = readLine()!!.toLong()
    	if (n<1000) println("${n}\n")
    	else if (n<995000) {
    		var num = (n+500)/1000
    		println("${num}K\n")
		}else {
			var num = (n+500000)/1000000
			println("${num}M\n")
		}
	}
}


fun main() {
    var t = readLine().toLong()
    while (t>0){
    	t--
    	var n = readLine().toLong()
    	if (n<1000) println("${n}\n")
    	else if (n<999500) {
    		var num = (n+500)/1000
    		println("${num}K\n")
		}else {
			var num = (n+500000)/1000000
			println("${num}M\n")
		}
	}
}


fun main() {
    var t = readLine()!!.toLong()
    while (t>0){
    	t--
    	var n = readLine()!!.toLong()
    	if (n<1000) println("${n}\n")
    	else if (n<995000) {
    		var num = (n+500)/1000
    		println("${num}K\n")
		}else {
			var num = (n+500000)/1000000
			println("${num}M\n")
		}
	}
}


import java.util.*
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }
val OUT = mutableSetOf<String>()

fun solve() {
  var n = nextLong()
  if (n >= 500000L) {
    if (n % 1000000L >= 500000L)
      n = (n / 1000000L + 1) * 1000000L
    println("${n/1000000L}M")
  } else if (n >= 1000L) {
    if (n % 1000L >= 500L)
      n = (n / 1000L + 1) * 1000L
    println("${n/1000L}K")
  } else {
    println("$n")
  }
}

fun main() {
  var T = nextInt()
  for (i in 1..T) {
    solve()
  }
}


import java.util.*
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }
val OUT = mutableSetOf<String>()

fun solve() {
  var n = nextLong()
  if (n >= 500000L) {
    if (n % 1000000L >= 500000L)
      n = (n / 1000000L + 1) * 1000000L
    OUT += "${n/1000000L}M"
    return
  }
  if (n >= 500L) {
    if (n % 1000L >= 500L)
      n = (n / 1000L + 1) * 1000L
    OUT += "${n/1000L}K"
    return
  }
  OUT += "$n"
}

fun main() {
  var T = nextInt()
  for (i in 1..T) {
    solve()
  }
  println(OUT.joinToString("\n"))
}


import java.util.*
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }
val OUT = mutableSetOf<String>()

fun solve() {
  var n = nextLong()
  if (n >= 500000L) {
    if (n % 1000000L >= 500000L)
      n = (n / 1000000L + 1) * 1000000L
    OUT += "${n/1000000L}M"
    return
  } else if (n >= 1000L) {
    if (n % 1000L >= 500L)
      n = (n / 1000L + 1) * 1000L
    OUT += "${n/1000L}K"
    return
  } else {
    OUT += "$n"
  }
}

fun main() {
  var T = nextInt()
  for (i in 1..T) {
    solve()
  }
  println(OUT.joinToString("\n"))
}


import java.util.*
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }
val OUT = mutableSetOf<String>()

fun solve() {
  var n = nextLong()
  if (n >= 1000000L) {
    if (n % 1000000L >= 500000L)
      n = (n / 1000000L + 1) * 1000000L
    println("${n/1000000L}M")
  } else if (n >= 1000L) {
    if (n % 1000L >= 500L)
      n = (n / 1000L + 1) * 1000L
    if (n / 1000L == 1000L)
      println("1M")
    else
      println("${n/1000L}K")
  } else {
    println("$n")
  }
}

fun main() {
  var T = nextInt()
  for (i in 1..T) {
    solve()
  }
}


import java.util.*
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }
val OUT = mutableSetOf<String>()

fun solve() {
  var n = nextLong()
  if (n >= 1000000L) {
    if (n % 1000000L >= 500000L)
      n = (n / 1000000L + 1) * 1000000L
    println("${n/1000000L}M")
  } else if (n >= 1000L) {
    if (n % 1000L >= 500L)
      n = (n / 1000L + 1) * 1000L
    println("${n/1000L}K")
  } else {
    println("$n")
  }
}

fun main() {
  var T = nextInt()
  for (i in 1..T) {
    solve()
  }
}


import java.util.*
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun nextInts() = next().split(" ").map { it.toInt() }
fun nextLongs() = next().split(" ").map { it.toLong() }
val OUT = mutableSetOf<String>()

fun solve() {
  var n = nextLong()
  if (n >= 500000L) {
    if (n % 1000000L >= 500000L)
      n = (n / 1000000L + 1) * 1000000L
    OUT += "${n/1000000L}M"
    return
  }
  if (n >= 1000L) {
    if (n % 1000L >= 500L)
      n = (n / 1000L + 1) * 1000L
    OUT += "${n/1000L}K"
    return
  }
  OUT += "$n"
}

fun main() {
  var T = nextInt()
  for (i in 1..T) {
    solve()
  }
  println(OUT.joinToString("\n"))
}


import java.util.Scanner

fun main(args: Array<String>){
    val input = Scanner(System.`in`)
    var test = input.nextInt()
    while(test >= 1)
    {
        test--
        var usu = input.nextInt()
        if(usu < 1000)
        	print(usu)
        else
        {
            if(usu > 999499)
            {
                if(usu % 1000000 <= 499999)
                {
                    print(usu/1000000)
                    print('M')
                }
                else
                {
                    print(usu/1000001)
                    print('M')
                }
            }
            else
            {
                if(usu % 1000 <= 501)
                {
                    print(usu/1000)
                    print('K')
                }
                else
                {
                    print(usu/10011)
                    print('K')
                }
            }
        }
        println()
    }
}


import java.util.Scanner

fun main(args: Array<String>){
val input = Scanner(System.`in`)
var test = input.nextInt()
while(test >= 1)
{
test--
var usu = input.nextInt()
if(usu < 1000)
print(usu)
else
{
if(usu > 999499)
{
if(usu % 1000000 <= 499999)
{
print(usu/1000000)
print('M')
}
else
{
print(1+usu/1000000)
print('M')
}
}
else
{
if(usu % 1000 <= 499)
{
print(usu/1000)
print('K')
}
else
{
print(1+usu/1000)
print('K')
}
}
}
println()}
}


import java.util.Scanner
fun main(args: Array<String>){
    val InFile = Scanner(System.`in`)
    var test = InFile.nextInt()
	while(test > 0)
	{
		var val = InFile.nextInt()
		if(val<1000)
		print(val)
		else
		{
			if(val<999500)
			{
				if(val%1000<500)
				{
					print(val/1000)
					print('K')
				}
			}
			else
			{
				print(val/1000+1)
				print('K')
			}
		}
		else
		{
			if(val%1000000<500000)
			{
				print(val/1000000)
				print('M')
			}
			else
			{
				print(val/1000000+1)
				print('M')
			}
		}
		}
			println()
			test--
			}
	}


import java.util.Scanner

fun main(args: Array<String>)
{
val input = Scanner(System.`in`)
var test = input.nextInt()
while(test >= 1)
{
test--
var usu = input.nextInt()
if(usu < 1000)
print(usu)
else
if(usu > 999499)
{
if(usu % 1000000 <= 499999)
{
print(usu/1000000)
print('M')
}
else
{
print(usu/1000001)
print('M')
}
}
else
{
if(usu % 1000 <= 501)
{
print(usu/1000)
print('K')
}
else
{
print(usu/1001)
print('K')
}
}
println()
}
}


import java.util.Scanner
fun main(args: Array<String>){
    xv InFile = Scanner(System.`in`)
    var test = InFile.nextInt()
	while(test > 0)
	{
		var xv = InFile.nextInt()
		if(xv<1000)
		print(xv)
		else
		{
			if(xv<999500)
			{
				if(xv%1000<500)
				{
					print(xv/1000)
					print('K')
				}
			}
			else
			{
				print(xv/1000+1)
				print('K')
			}
		}
		else
		{
			if(xv%1000000<500000)
			{
				print(xv/1000000)
				print('M')
			}
			else
			{
				print(xv/1000000+1)
				print('M')
			}
		}
		}
			println()
			test--
			}
	}


import java.util.Scanner
fun main(args: Array<String>){
    val InFile = Scanner(System.`in`)
    var test = InFile.nextInt()
while(test > 0)
{
var val = InFile.nextInt()
if(val<1000)
print(val)
else
{
if(val<999500)
if(val%1000<500)
{
print(val/1000)
print('K')
}
else
{
print(val/1000+1)
print('K')
}
}
else
{
if(val%1000000<500000)
{
print(val/1000000)
print('M')
}
else
{
print(val/1000000+1)
print('M')
}
}
}
println()
test--
}
}


package kotlin_hero

import java.util.*
import kotlin.math.ceil
import kotlin.math.round

object program {

    @JvmStatic
    fun main(args: Array<String>) {

        val scanner = Scanner(System.`in`)
        var t = scanner.nextInt()

        while (t-- > 0) {
            var n = scanner.nextInt()
            when {
                n > 999499 -> {
                    var f: Double = n.toDouble()
                    f/= 1000000
                    n = (f + .5).toInt()
                    println("${n}M")
                }
                n > 999 -> {
                    var f: Double = n.toDouble()
                    f/= 1000
                    n = (f + .5).toInt()
                    println("${n}K")
                }
                else -> {
                    println(n)
                }
            }
        }
    }
}


package kotlin_hero

import java.util.*
import kotlin.math.ceil
import kotlin.math.round

object A {

    @JvmStatic
    fun main(args: Array<String>) {

        val scanner = Scanner(System.`in`)
        var t = scanner.nextInt()

        while (t-- > 0) {
            var n = scanner.nextInt()
            when {
                n > 999499 -> {
                    var f: Double = n.toDouble()
                    f/= 1000000
                    n = (f + .5).toInt()
                    println("${n}M")
                }
                n > 999 -> {
                    var f: Double = n.toDouble()
                    f/= 1000
                    n = (f + .5).toInt()
                    println("${n}K")
                }
                else -> {
                    println(n)
                }
            }
        }
    }
}


package kotlin_hero

import java.util.*
import kotlin.math.ceil
import kotlin.math.round
class program {
    fun main() {
        val scanner = Scanner(System.`in`)
        var t = scanner.nextInt()

        while (t-- > 0) {
            var n = scanner.nextInt()
            when {
                n > 999499 -> {
                    var f: Double = n.toDouble()
                    f/= 1000000
                    n = (f + .5).toInt()
                    println("${n}M")
                }
                n > 999 -> {
                    var f: Double = n.toDouble()
                    f/= 1000
                    n = (f + .5).toInt()
                    println("${n}K")
                }
                else -> {
                    println(n)
                }
            }
        }
    }
}
object A {

    @JvmStatic
    fun main(args: Array<String>) {
        program().main()
    }
}


import java.util.*

fun main(args: Array<String>) {

        val scanner = Scanner(System.`in`)
        var t = scanner.nextInt()

        while (t-- > 0) {
            var n = scanner.nextInt()
            when {
                n > 999499 -> {
                    var f: Double = n.toDouble()
                    f/= 1000000
                    n = (f + .5).toInt()
                    println("${n}M")
                }
                n > 999 -> {
                    var f: Double = n.toDouble()
                    f/= 1000
                    n = (f + .5).toInt()
                    println("${n}K")
                }
                else -> {
                    println(n)
                }
            }
        }
    }


package kotlin_hero

import java.util.*
import kotlin.math.ceil
import kotlin.math.round
class program {
    fun main() {
        val scanner = Scanner(System.`in`)
        var t = scanner.nextInt()

        while (t-- > 0) {
            var n = scanner.nextInt()
            when {
                n > 999499 -> {
                    var f: Double = n.toDouble()
                    f/= 1000000
                    n = (f + .5).toInt()
                    println("${n}M")
                }
                n > 999 -> {
                    var f: Double = n.toDouble()
                    f/= 1000
                    n = (f + .5).toInt()
                    println("${n}K")
                }
                else -> {
                    println(n)
                }
            }
        }
    }
}


import kotlin.math.ceil
import kotlin.math.round

private fun main() {
    solve(StdInput)

}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> {
                val divided = value / 1000
                val rest = value - divided*1000
                val r = if (rest >=500) ceil(value / 1000.0).toInt().toString() + "K" else round(value / 1000.0).toInt().toString() + "K"
                if (r == "1000K") "1M" else r
            }
            in 1_000_000..2_000_000_000 -> {
                val divided = value / 1_000_000
                val rest = value - divided*1_000_000
                if (rest >= 500000) ceil(value/1000000.0).toInt().toString() + "M" else round(value/1000000.0).toInt().toString() + "M"
            }
            else -> "2M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
10
999
123
0
1782
31415926
1500
999999
35499710
2000000000
4500000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


import kotlin.math.round

private fun main() {
    solve(StdInput)

}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> round(value/1000.0).toInt().toString() + "K"
            else -> round(value/1000000.0).toInt().toString() + "M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
9
999
123
0
1782
31415926
1500
999999
35499710
2000000000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


package org.ehmeed.competitive.kotlinheroes.third

import kotlin.math.ceil
import kotlin.math.round

private fun main() {
//    solve(StdInput)
    solveTestInputs()
}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> {
                val divided = value / 1000
                val rest = value - divided*1000
                val r = if (rest >=500) ceil(value / 1000.0).toInt().toString() + "K" else round(value / 1000.0).toInt().toString() + "K"
                if (r == "1000K") "1M" else r
            }
            in 1_000_000..2_000_000_000 -> {
                val divided = value / 1_000_000
                val rest = value - divided*1_000_000
                if (rest >= 500000) ceil(value/1000000.0).toInt().toString() + "M" else round(value/1000000.0).toInt().toString() + "M"
            }
            else -> "2M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
10
999
123
0
1782
31415926
1500
999999
35499710
2000000000
4500000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


import kotlin.math.ceil
import kotlin.math.round

private fun main() {
    solve(StdInput)
}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> {
                val r = ceil(value/1000.0).toInt().toString() + "K"
                if (r == "1000K") "1M" else r
            }
            in 1_000_000..2_000_000_000 -> ceil(value/1000000.0).toInt().toString() + "M"
            else -> "2M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
10
999
123
0
1782
31415926
1500
999999
35499710
2000000000
4500000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


import kotlin.math.ceil
import kotlin.math.round

private fun main() {
    solve(StdInput)

}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> {
                val divided = value / 1000.0
                val rest = value - divided*1000.0
                val r = if (rest >=500) ceil(divided).toInt().toString() + "K" else round(divided).toInt().toString() + "K"
                if (r == "1000K") "1M" else r
            }
            in 1_000_000..2_000_000_000 -> {
                val divided = value / 1_000_000
                val rest = value - divided*1_000_000
                if (rest >= 500000) ceil(value/1000000.0).toInt().toString() + "M" else round(value/1000000.0).toInt().toString() + "M"
            }
            else -> "2M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
10
999
123
0
1782
31415926
1500
999999
35499710
2000000000
4500000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


import kotlin.math.round

private fun main() {
    solve(StdInput)
//    solveTestInputs()
}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> {
                val r = round(value/1000.0).toInt().toString() + "K"
                if (r == "1000K") "1M" else r
            }
            in 1_000_000..2_000_000_000 -> round(value/1000000.0).toInt().toString() + "M"
            else -> "2M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
9
999
123
0
1782
31415926
1500
999999
35499710
2000000000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


import kotlin.math.round

private fun main() {
    solve(StdInput)

}

private fun solve(input: Input) {
    val t = input.nextLine().toInt()
    repeat(t) {
        val value = input.nextLine().toInt()
        val result = when(value) {
            in 0..999 -> value.toString()
            in 1000..999_999 -> {
                val r = round(value/1000.0).toInt().toString() + "K"
                if (r == "1000K") "1M" else r
            }
            else -> round(value/1000000.0).toInt().toString() + "M"
        }
        println(result)
    }
}

// test inputs
private fun solveTestInputs() {
    listOf(
        """
9
999
123
0
1782
31415926
1500
999999
35499710
2000000000

        """,
        """

        """,
        """

        """
    )
        .filter { it.isNotBlank() }
        .map { it.trimIndent().trimEnd() }
        .map { it.asTestInput() }
        .mapIndexed(::solveTestInput)

}

private const val DELIMITER = "----------------------------------------------"
private fun solveTestInput(index: Int, input: TestInput) {
    println("$DELIMITER INPUT: $index $DELIMITER")
    println(input.input)
    println("$DELIMITER SOLUTION: $index $DELIMITER")
    solve(input)
}

private fun String.toInts() = split(" ").map { it.toInt() }

private interface Input {
    fun nextLine(): String
}

private object StdInput : Input {
    override fun nextLine(): String = readLine()!!
}

private class TestInput(val input: String) : Input {
    private val iterator = input.split('\n').iterator()
    override fun nextLine(): String = iterator.next()
}

private fun String.asTestInput() = TestInput(this)


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while(t > 0) {
        val cur = readInt()
        when {
            cur <= 949 -> println(cur)
            cur <= 999499 -> {
                val cur1 = round(cur.toDouble() / 1000.toDouble())
                println("${cur1.toInt()}K")
            }
            else -> {
                val cur1 = round(cur.toDouble() / 1000000.toDouble())
                println("${cur1.toInt()}M")
            }
        }
        t--
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round
import kotlin.math.roundToInt

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while (t > 0) {
        val cur = readInt()
        when {
            cur <= 999 -> println(cur)
            cur <= 999500 -> {
                val cur1 = (cur.toDouble() / 1000.toDouble()).roundToInt()
                println("${cur1}K")
            }
            else -> {
                val cur1 = (cur.toDouble() / 1000000.toDouble()).roundToInt()
                println("${cur1}M")
            }
        }
        t--
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while(t >= 0) {
        val cur = readInt()
        when {
            cur <= 999 -> println(cur)
            cur <= 999000 -> {
                val cur1 = round(cur.toDouble() / 1000.toDouble())
                println("${cur1.toInt()}K")
            }
            else -> {
                val cur1 = round(cur.toDouble() / 1000000.toDouble())
                println("${cur1.toInt()}M")
            }
        }
        t--
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while(t > 0) {
        val cur = readInt()
        when {
            cur <= 999 -> println(cur)
            cur <= 999500 -> {
                val cur1 = round(cur.toDouble() / 1000.toDouble())
                println("${cur1.toInt()}K")
            }
            else -> {
                val cur1 = round(cur.toDouble() / 1000000.toDouble())
                println("${cur1.toInt()}M")
            }
        }
        t--
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    val cur = readInt()
    when {
        cur <= 999 -> println(cur)
        cur <= 999000 -> {
            val cur1 = ceil(cur.toDouble() / 1000.toDouble())
            println("${cur1.toInt()}K")
        }
        else -> {
            val cur1 = ceil(cur.toDouble() / 1000000.toDouble())
            println("${cur1.toInt()}M")
        }
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while(t > 0) {
        val cur = readInt()
        when {
            cur <= 999 -> println(cur)
            cur <= 999000 -> {
                val cur1 = round(cur.toDouble() / 1000.toDouble())
                println("${cur1.toInt()}K")
            }
            else -> {
                val cur1 = round(cur.toDouble() / 1000000.toDouble())
                println("${cur1.toInt()}M")
            }
        }
        t--
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while(t > 0) {
        val cur = readInt()
        when {
            cur <= 999 -> println(cur)
            cur <= 999499 -> {
                val cur1 = round(cur.toDouble() / 1000.toDouble())
                println("${cur1.toInt()}K")
            }
            else -> {
                val cur1 = round(cur.toDouble() / 1000000.toDouble())
                println("${cur1.toInt()}M")
            }
        }
        t--
    }
}


import java.io.PrintWriter
import java.util.*
import kotlin.math.ceil
import kotlin.math.round
import kotlin.math.roundToInt

@JvmField
val INPUT = System.`in`
@JvmField
val OUTPUT = System.out

@JvmField
val _reader = INPUT.bufferedReader()

fun readLine(): String? = _reader.readLine()
fun readLn() = _reader.readLine()!!
@JvmField
var _tokenizer: StringTokenizer = StringTokenizer("")

fun read(): String {
    while (_tokenizer.hasMoreTokens().not()) _tokenizer = StringTokenizer(_reader.readLine() ?: return "", " ")
    return _tokenizer.nextToken()
}

fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField
val _writer = PrintWriter(OUTPUT, false)

inline fun output(block: PrintWriter.() -> Unit) {
    _writer.apply(block).flush()
}

fun main() {
    var t = readInt()
    while (t > 0) {
        val cur = readInt()
        when {
            cur <= 999 -> println(cur)
            cur < 999500 -> {
                val cur1 = (cur.toDouble() / 1000.toDouble()).roundToInt()
                println("${cur1}K")
            }
            else -> {
                val cur1 = (cur.toDouble() / 1000000.toDouble()).roundToInt()
                println("${cur1}M")
            }
        }
        t--
    }
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.min

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main() {

    val TC = readInt()
    for (tc in 0 until TC) {
        val n = readInt()
        if (n < 1000) println(n)
        else if (n < 1000000) println("${n / 1000}K")
        else println("${n / 1000000}M")
    }
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.min
import kotlin.math.round

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main() {

    val TC = readInt()
    for (tc in 0 until TC) {
        val n = readInt()
        when {
            n < 1000 -> println(n)
            n < 999500 -> println("${n / 1000 + (if (n%1000 >= 500) 1 else 0)}K")
            else -> println("${n / 1000000 + (if (n%1000000 >= 500000) 1 else 0)}M")
        }
    }
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.min
import kotlin.math.round

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main() {

    val TC = readInt()
    for (tc in 0 until TC) {
        val n = readInt()
        if (n < 1000) println(n)
        else if (n < 999500) println("${round(n / 1000.0 + 1e-6).toInt()}K")
        else println("${round(n / 1000000.0 + 1e-6).toInt()}M")
    }
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.min
import kotlin.math.round

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main() {

    val TC = readInt()
    for (tc in 0 until TC) {
        val n = readInt()
        if (n < 1000) println(n)
        else if (n < 999500) println("${round(n / 1000.0).toInt()}K")
        else println("${round(n / 1000000.0).toInt()}M")
    }
}


import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.min
import kotlin.math.round

private fun readLn() = readLine()!! // string line
private fun readInt() = readLn().toInt() // single int
private fun readLong() = readLn().toLong() // single int
private fun readStrings() = readLn().split(" ") // list of strings
private fun readInts() = readStrings().map { it.toInt() } // list of ints

fun main() {

    val TC = readInt()
    for (tc in 0 until TC) {
        val n = readInt()
        if (n < 1000) println(n)
        else if (n < 1000000) println("${round(n / 1000.0).toInt()}K")
        else println("${round(n / 1000000.0).toInt()}M")
    }
}


import java.io.*
import java.util.*

object programkt {
    const val BUFFER_SIZE = 1024

    internal class FastWriter(outputStream: OutputStream) {
        private val writer = PrintWriter(BufferedWriter(OutputStreamWriter(outputStream)))
        fun print(vararg objects: Any) {
            for (i in objects.indices) {
                if (i != 0) {
                    writer.print(' ')
                }
                writer.print(objects[i])
            }
        }

        fun printLine(vararg objects: Any) {
            print(*objects)
            writer.println()
        }

        fun close() {
            writer.close()
        }

        fun printLine(i: Int) {
            writer.println(i)
        }
    }

    internal class FastReader(private val stream: InputStream) {
        private val buf = ByteArray(BUFFER_SIZE)
        private var curChar: Int = 0
        private var numChars: Int = 0
        private val filter: FastReader.SpaceCharFilter? = null
        fun read(): Int {
            if (numChars == -1) throw InputMismatchException()

            if (curChar >= numChars) {
                curChar = 0
                try {
                    numChars = stream.read(buf)
                } catch (e: IOException) {
                    throw InputMismatchException()
                }
                if (numChars <= 0) return -1
            }
            return buf[curChar++].toInt()
        }

        fun readInt(): Int {
            var c = read()
            while (isSpaceChar(c)) {
                c = read()
            }
            var sgn = 1
            if (c == '-'.toInt()) {
                sgn = -1
                c = read()
            }
            var res = 0
            do {
                if (c < '0'.toInt() || c > '9'.toInt()) throw InputMismatchException()
                res *= 10
                res += c - '0'.toInt()
                c = read()
            } while (!isSpaceChar(c))
            return res * sgn
        }

        fun readString(): String {
            var c = read()
            while (isSpaceChar(c)) {
                c = read()
            }
            val res = StringBuilder()
            do {
                if (Character.isValidCodePoint(c)) {
                    res.appendCodePoint(c)
                }
                c = read()
            } while (!isSpaceChar(c))
            return res.toString()
        }

        fun isSpaceChar(c: Int): Boolean = filter?.isSpaceChar(c) ?: isWhitespace(c)
        operator fun next(): String = readString()
        interface SpaceCharFilter {
            fun isSpaceChar(ch: Int): Boolean
        }

        companion object {
            fun isWhitespace(c: Int): Boolean =
                c == ' '.toInt() || c == '\n'.toInt() || c == '\r'.toInt() || c == '\t'.toInt() || c == -1
        }
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val inputStream = System.`in`
        val outputStream = System.out
        val input = FastReader(inputStream)
        val output = FastWriter(outputStream)
        repeat(input.readInt()) {
            val a = input.readInt()
            when {
                a < 1000 -> {
                    output.printLine(a)
                }
                a < 999500 -> {
                    output.printLine("${(a + 500) / 1000}K")
                }
                else -> {
                    output.printLine("${(a + 500000) / 1000000}M")
                }
            }
        }
    }
}


import java.io.BufferedWriter
import java.io.IOException
import java.io.InputStream
import java.io.OutputStreamWriter
import java.io.PrintStream
import java.io.PrintWriter
import java.util.*

class FastWriter(outputStream: PrintStream = System.out) {
    private val writer = PrintWriter(BufferedWriter(OutputStreamWriter(outputStream)))
    fun close() = writer.close()
    fun println(i: Int) = writer.println(i)
    fun println(s: String) = writer.println(s)

    companion object {
        fun create(): FastWriter = FastWriter()
    }
}

class FastReader(private val stream: InputStream = System.`in`) {
    private val buf = ByteArray(1024)
    private var curChar: Int = 0
    private var numChars: Int = 0
    fun readIntArrays(vararg arrays: IntArray) {
        for (i in arrays[0].indices) {
            for (j in arrays.indices) {
                arrays[j][i] = readInt()
            }
        }
    }

    fun readInt(): Int {
        var c = read()
        while (isSpaceChar(c)) {
            c = read()
        }
        var sgn = 1
        if (c == '-'.toInt()) {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0'.toInt() || c > '9'.toInt()) {
                throw InputMismatchException()
            }
            res *= 10
            res += c - '0'.toInt()
            c = read()
        } while (!isSpaceChar(c))
        return res * sgn
    }

    fun readString(): String {
        var c = read()
        while (isSpaceChar(c)) {
            c = read()
        }
        val res = StringBuilder()
        do {
            if (Character.isValidCodePoint(c)) {
                res.appendCodePoint(c)
            }
            c = read()
        } while (!isSpaceChar(c))
        return res.toString()
    }

    operator fun next(): String = readString()
    private fun read(): Int {
        if (numChars == -1) {
            throw InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = stream.read(buf)
            } catch (e: IOException) {
                throw InputMismatchException()
            }

            if (numChars <= 0) {
                return -1
            }
        }
        return buf[curChar++].toInt()
    }

    private fun isSpaceChar(c: Int): Boolean =
        c == ' '.toInt() || c == '\n'.toInt() || c == '\r'.toInt() || c == '\t'.toInt() || c == -1
}

fun main() {
    val input = FastReader()
    val output = FastWriter()
    repeat(input.readInt()) {
        f(input, output)
    }
}

fun f(inputReader: FastReader, outputWriter: FastWriter) {
    val a = inputReader.readInt()
    when {
        a < 1000 -> {
            outputWriter.println(a)
        }
        a < 999500 -> {
            outputWriter.println("${(a + 500) / 1000}K")
        }
        else -> {
            outputWriter.println("${(a + 500000) / 1000000}M")
        }
    }
}


import java.io.*
import java.util.*

object programkt {
    const val BUFFER_SIZE = 1024

    internal class FastWriter(outputStream: OutputStream) {
        private val writer = PrintWriter(BufferedWriter(OutputStreamWriter(outputStream)))
        fun print(vararg objects: Any) {
            for (i in objects.indices) {
                if (i != 0) {
                    writer.print(' ')
                }
                writer.print(objects[i])
            }
        }

        fun printLine(vararg objects: Any) {
            print(*objects)
            writer.println()
        }

        fun close() {
            writer.close()
        }

        fun printLine(i: Int) {
            writer.println(i)
        }
    }

    internal class FastReader(private val stream: InputStream) {
        private val buf = ByteArray(BUFFER_SIZE)
        private var curChar: Int = 0
        private var numChars: Int = 0
        private val filter: FastReader.SpaceCharFilter? = null
        fun read(): Int {
            if (numChars == -1) throw InputMismatchException()

            if (curChar >= numChars) {
                curChar = 0
                try {
                    numChars = stream.read(buf)
                } catch (e: IOException) {
                    throw InputMismatchException()
                }
                if (numChars <= 0) return -1
            }
            return buf[curChar++].toInt()
        }

        fun readInt(): Int {
            var c = read()
            while (isSpaceChar(c)) {
                c = read()
            }
            var sgn = 1
            if (c == '-'.toInt()) {
                sgn = -1
                c = read()
            }
            var res = 0
            do {
                if (c < '0'.toInt() || c > '9'.toInt()) throw InputMismatchException()
                res *= 10
                res += c - '0'.toInt()
                c = read()
            } while (!isSpaceChar(c))
            return res * sgn
        }

        fun readString(): String {
            var c = read()
            while (isSpaceChar(c)) {
                c = read()
            }
            val res = StringBuilder()
            do {
                if (Character.isValidCodePoint(c)) {
                    res.appendCodePoint(c)
                }
                c = read()
            } while (!isSpaceChar(c))
            return res.toString()
        }

        fun isSpaceChar(c: Int): Boolean = filter?.isSpaceChar(c) ?: isWhitespace(c)
        operator fun next(): String = readString()
        interface SpaceCharFilter {
            fun isSpaceChar(ch: Int): Boolean
        }

        companion object {
            fun isWhitespace(c: Int): Boolean =
                c == ' '.toInt() || c == '\n'.toInt() || c == '\r'.toInt() || c == '\t'.toInt() || c == -1
        }
    }

    @JvmStatic
    fun main(args: Array<String>) {
        val inputStream = System.`in`
        val outputStream = System.out
        val input = FastReader(inputStream)
        val output = FastWriter(outputStream)
        repeat(input.readInt()) {
            val a = input.readInt()
            when {
                a < 1000 -> {
                    output.printLine(a)
                }
                a < 999500 -> {
                    output.printLine("${(a + 500) / 1000}K")
                }
                else -> {
                    output.printLine("${(a + 500000) / 1000000}M")
                }
            }
        }
        output.close()

    }
}


package org.example

import java.io.IOException
import java.io.InputStream
import java.io.PrintStream
import java.io.PrintWriter
import java.util.*

class FastWriter(outputStream: PrintStream = System.out) {
    private val writer = PrintWriter(outputStream)
    fun close() = writer.close()
    fun println(i: Int) = writer.println(i)
    fun println(s: String) = writer.println(s)

    companion object {
        fun create(): FastWriter = FastWriter()
    }
}

class FastReader(private val stream: InputStream = System.`in`) {
    private val buf = ByteArray(1024)
    private var curChar: Int = 0
    private var numChars: Int = 0
    fun readIntArrays(vararg arrays: IntArray) {
        for (i in arrays[0].indices) {
            for (j in arrays.indices) {
                arrays[j][i] = readInt()
            }
        }
    }

    fun readInt(): Int {
        var c = read()
        while (isSpaceChar(c)) {
            c = read()
        }
        var sgn = 1
        if (c == '-'.toInt()) {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0'.toInt() || c > '9'.toInt()) {
                throw InputMismatchException()
            }
            res *= 10
            res += c - '0'.toInt()
            c = read()
        } while (!isSpaceChar(c))
        return res * sgn
    }

    fun readString(): String {
        var c = read()
        while (isSpaceChar(c)) {
            c = read()
        }
        val res = StringBuilder()
        do {
            if (Character.isValidCodePoint(c)) {
                res.appendCodePoint(c)
            }
            c = read()
        } while (!isSpaceChar(c))
        return res.toString()
    }

    operator fun next(): String = readString()
    private fun read(): Int {
        if (numChars == -1) {
            throw InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = stream.read(buf)
            } catch (e: IOException) {
                throw InputMismatchException()
            }

            if (numChars <= 0) {
                return -1
            }
        }
        return buf[curChar++].toInt()
    }

    private fun isSpaceChar(c: Int): Boolean =
        c == ' '.toInt() || c == '\n'.toInt() || c == '\r'.toInt() || c == '\t'.toInt() || c == -1
}

fun main() {
    val input = FastReader()
    val output = FastWriter()
    repeat(input.readInt()) {
        f(input, output)
    }
}

fun f(inputReader: FastReader, outputWriter: FastWriter) {
    val a = inputReader.readInt()
    when {
        a < 1000 -> {
            outputWriter.println(a)
        }
        a < 999500 -> {
            outputWriter.println("${(a + 500) / 1000}K")
        }
        else -> {
            outputWriter.println("${(a + 500000) / 1000000}M")
        }
    }
}