#include<bits/stdc++.h>
#define F first
#define S second
#define endl "\n"
#define Endl "\n"
#define lop(i,n) for(i=0;i<n;i++)
#define lop1(i,n) for(i=1;i<=n;i++)
#define lopxy(i,x,y) for(i=x;i<y;i++)
#define ll long long
#define vl vector<long long>
#define pll pair<long long,long long>
#define sl set<long long>
#define uset unordered_set<long long>
#define umap unordered_map
#define prq priority_queue
#define pqll priority_queue<ll>
#define hell 1000000007
#define mod 998244353
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define N 100000
#define N2 200000
#define bpc(x) __builtin_popcount(x)
#define inf 1e16
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define all(v) (v).begin(),(v).end()
#define D1(x) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<endl
#define D2(x,y) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<" "<<#y<<"="<<y<<endl
#define D3(x,y,z) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<" "<<#y<<"="<<y<<" "<<#z<<"="<<z<<endl
using namespace std;
ll power(ll x, ll y)
{
    if (y == 0)
        return 1;
    else if (y % 2 == 0)
        return (power(x, y / 2) * power(x, y / 2)) % mod;
    else
        return ((x * power(x, y / 2)) % mod * power(x, y / 2)) % mod;
}
ll power(ll x, ll y, ll p)
{
    ll res = 1;
    x = x % p;
    while (y > 0)
    {
        if (y & 1)
            res = (res*x) % p;
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}

// Returns n^(-1) mod p
ll modInverse(ll n, ll p)
{
    return power(n, p-2, p);
}

// Returns nCr % p using Fermat's little theorem.
ll fac[N+1];
void pre(ll p){
    fac[0] = 1;
    for (ll i=1 ; i<=N; i++)
        fac[i] = (fac[i-1]*i)%p;
}
ll nCrModPFermat(ll n, ll r, ll p)
{
   if (r==0)
      return 1;
    if(r>n)
      return 0;
    return (fac[n]* modInverse(fac[r], p) % p * modInverse(fac[n-r], p) % p) % p;
}
ll primes[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113};
bool isprime(ll n){
    if(n<=1)
        return false;
    for(ll i=2;i<=sqrt(n);i++){
        if(n%i==0)
            return false;
    }
    return true;
}
ll find(ll n){
    for(auto it:primes){
        if(it-n+1<0)
            continue;
        if(!isprime(it-n+1))
            return it-n+1;
    }
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt.txt","r",stdin);
    freopen("output.txt.txt","w",stdout);
    freopen("error.txt","w",stderr);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    ll t,n,i,j;
    cin>>t;
    while(t--){
        cin>>n;
        ll x=find(n);
        ll c=0;
        for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                if(j==i)
                    cout<<x;
                else cout<<1;
                cout<<" ";
            }
            cout<<endl;
        }
    }
    cerr<<(1000*clock())/CLOCKS_PER_SEC<<"ms";
    return 0;
}


#include<bits/stdc++.h>
#define F first
#define S second
#define endl "\n"
#define Endl "\n"
#define lop(i,n) for(i=0;i<n;i++)
#define lop1(i,n) for(i=1;i<=n;i++)
#define lopxy(i,x,y) for(i=x;i<y;i++)
#define ll long long
#define vl vector<long long>
#define pll pair<long long,long long>
#define sl set<long long>
#define uset unordered_set<long long>
#define umap unordered_map
#define prq priority_queue
#define pqll priority_queue<ll>
#define hell 1000000007
#define mod 998244353
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define N 100000
#define N2 200000
#define bpc(x) __builtin_popcount(x)
#define inf 1e16
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define all(v) (v).begin(),(v).end()
#define D1(x) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<endl
#define D2(x,y) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<" "<<#y<<"="<<y<<endl
#define D3(x,y,z) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<" "<<#y<<"="<<y<<" "<<#z<<"="<<z<<endl
using namespace std;
ll power(ll x, ll y)
{
    if (y == 0)
        return 1;
    else if (y % 2 == 0)
        return (power(x, y / 2) * power(x, y / 2)) % mod;
    else
        return ((x * power(x, y / 2)) % mod * power(x, y / 2)) % mod;
}
ll power(ll x, ll y, ll p)
{
    ll res = 1;
    x = x % p;
    while (y > 0)
    {
        if (y & 1)
            res = (res*x) % p;
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}

// Returns n^(-1) mod p
ll modInverse(ll n, ll p)
{
    return power(n, p-2, p);
}

// Returns nCr % p using Fermat's little theorem.
ll fac[N+1];
void pre(ll p){
    fac[0] = 1;
    for (ll i=1 ; i<=N; i++)
        fac[i] = (fac[i-1]*i)%p;
}
ll nCrModPFermat(ll n, ll r, ll p)
{
   if (r==0)
      return 1;
    if(r>n)
      return 0;
    return (fac[n]* modInverse(fac[r], p) % p * modInverse(fac[n-r], p) % p) % p;
}
vl primes;
void sieve(){
    ll pr[100001];
    mem0(pr);
    for(ll i=2;i<=N;i++){
        if(pr[i]==1)
            continue;
        for(ll j=i*i;j<=n;j++){
            pr[j]=1;
        }
        if(pr[i]==0)
            primes.pb(i);
    }
}
bool isprime(ll n){
    if(n<=1)
        return false;
    for(ll i=2;i<=sqrt(n);i++){
        if(n%i==0)
            return false;
    }
    return true;
}
ll find(ll n){
    for(auto it:primes){
        if(it-n+1<0)
            continue;
        if(!isprime(it-n+1))
            return it-n+1;
    }
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt.txt","r",stdin);
    freopen("output.txt.txt","w",stdout);
    freopen("error.txt","w",stderr);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    ll t,n,i,j;
    cin>>t;
    while(t--){
        cin>>n;
        ll x=find(n);
        ll c=0;
        for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                if(j==i)
                    cout<<x;
                else cout<<1;
                cout<<" ";
            }
            cout<<endl;
        }
    }
    cerr<<(1000*clock())/CLOCKS_PER_SEC<<"ms";
    return 0;
}


#include<bits/stdc++.h>
#define F first
#define S second
#define endl "\n"
#define Endl "\n"
#define lop(i,n) for(i=0;i<n;i++)
#define lop1(i,n) for(i=1;i<=n;i++)
#define lopxy(i,x,y) for(i=x;i<y;i++)
#define ll long long
#define vl vector<long long>
#define pll pair<long long,long long>
#define sl set<long long>
#define uset unordered_set<long long>
#define umap unordered_map
#define prq priority_queue
#define pqll priority_queue<ll>
#define hell 1000000007
#define mod 998244353
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define N 100000
#define N2 200000
#define bpc(x) __builtin_popcount(x)
#define inf 1e16
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define all(v) (v).begin(),(v).end()
#define D1(x) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<endl
#define D2(x,y) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<" "<<#y<<"="<<y<<endl
#define D3(x,y,z) cerr <<"At line "<<__LINE__<<" "<<#x<<"="<<x<<" "<<#y<<"="<<y<<" "<<#z<<"="<<z<<endl
using namespace std;
ll power(ll x, ll y)
{
    if (y == 0)
        return 1;
    else if (y % 2 == 0)
        return (power(x, y / 2) * power(x, y / 2)) % mod;
    else
        return ((x * power(x, y / 2)) % mod * power(x, y / 2)) % mod;
}
ll power(ll x, ll y, ll p)
{
    ll res = 1;
    x = x % p;
    while (y > 0)
    {
        if (y & 1)
            res = (res*x) % p;
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}

// Returns n^(-1) mod p
ll modInverse(ll n, ll p)
{
    return power(n, p-2, p);
}

// Returns nCr % p using Fermat's little theorem.
ll fac[N+1];
void pre(ll p){
    fac[0] = 1;
    for (ll i=1 ; i<=N; i++)
        fac[i] = (fac[i-1]*i)%p;
}
ll nCrModPFermat(ll n, ll r, ll p)
{
   if (r==0)
      return 1;
    if(r>n)
      return 0;
    return (fac[n]* modInverse(fac[r], p) % p * modInverse(fac[n-r], p) % p) % p;
}

bool isprime(ll n){
    if(n<=1)
        return false;
    for(ll i=2;i<=sqrt(n);i++){
        if(n%i==0)
            return false;
    }
    return true;
}
ll find(ll n){
    ll x=0;
    while(true){
        if(isprime(n-1+x)&&!isprime(x))
            return x;
        x++;
    }
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt.txt","r",stdin);
    freopen("output.txt.txt","w",stdout);
    freopen("error.txt","w",stderr);
    #endif
    ios_base::sync_with_stdio(0);

    cin.tie(0);
    cout.tie(0);

    ll t,n,i,j;
    cin>>t;
    while(t--){
        cin>>n;
        ll x=find(n);
        //cout<<x<<endl;

        for(i=0;i<n;i++){
            for(j=0;j<n;j++){
                if(j==i)
                    cout<<x;
                else cout<<1;
                cout<<" ";
            }
            cout<<endl;
        }
    }
    cerr<<(1000*clock())/CLOCKS_PER_SEC<<"ms";
    return 0;
}


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int t,i,g,a,u;
    cin>>t;
    int res[t],n[t];
    for (i=0;i<t;i++)
    {
        cin>>n[i];
        a=n[i];
        int flag=0; int flag1=1;
        while ((flag==0) and (a<=2009))
        {
            for (g=2;g<=sqrt(a);g++)
            {
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {a++;flag1=0;}
            else {flag=1;a=a-(n[i]-1);}
            if (flag==1)
            {
                for (g=2;g<=sqrt(a);g++)
                if (a%g==0) {flag1=1;}
            }
            if (flag1==0) {a++;flag=0;flag1=0;a=a+(n[i]-1);}
        }
        res[i]=a;
    }
    for (i=0;i<t;i++)
    {
        for (g=0;g<n[i];g++)
        {
            for (u=0;u<n[i];u++)
            {
                if (u==g) {cout<<res[i];}
                else {cout<<1;}
                cout<<" ";
            }
            cout<<endl;
        }
    }
}


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int t,i,g,a,u;
    cin>>t;
    int res[t],n[t];
    for (i=0;i<t;i++)
    {
        cin>>n[i];
        a=n[i];
        int flag=0; int flag1=1;
        while (flag==0)
        {
            for (g=2;g<=sqrt(a);g++)
            {
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {a++;flag1=0;}
            else {flag=1;a=a-(n[i]-1);}
            if (flag==1)
            {
                for (g=2;g<=sqrt(a);g++)
                if (a%g==0) {flag1=1;}
            }
            if (flag1==0) {a++;flag=0;flag1=0;a=a+(n[i]-1);}
        }
        res[i]=a;
    }
    for (i=0;i<t;i++)
    {
        for (g=0;g<n[i];g++)
        {
            for (u=0;u<n[i];u++)
            {
                if (u==g) {cout<<res[i];}
                else {cout<<1;}
                cout<<" ";
            }
            cout<<endl;
        }
    }
}


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int t,i,g,a,u;
    cin>>t;
    int res[t],n[t];
    for (i=0;i<t;i++)
    {
        cin>>n[i];
        a=n[i];
        int flag=0; int flag1=0;
        while (flag==0)
        {
            for (g=2;g<=sqrt(a);g++)
            {
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {++a;flag1=0;}
            else {flag=1;a=a-(n[i]-1);}
            if (flag==1)
            {
                for (g=2;g<=sqrt(a);g++)
                {
                    if (a%g==0) {flag1=1;}
                }
            if ((flag1==0) and (a!=1)) {++a;flag=0;flag1=0;a=a+(n[i]-1);}
            }
        }
        res[i]=a;
    }
    for (i=0;i<t;i++)
    {
        for (g=0;g<n[i];g++)
        {
            for (u=0;u<n[i];u++)
            {
                if (u==g) {cout<<res[i];}
                else {cout<<1;}
                cout<<" ";
            }
            cout<<endl;
        }
    }
}


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int t,i,g,a,u;
    cin>>t;
    int res[t],n[t];
    for (i=0;i<t;i++)
    {
        cin>>n[i];
        a=n[i];
        int flag=0; int flag1=1;
        while (flag==0)
        {
            for (g=2;g<=sqrt(a);g++)
            {
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {a++;flag1=0;}
            else {flag=1;a=a-(n[i]-1);}
            if (flag==1)
            {
                for (g=2;g<=sqrt(a);g++)
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {a++;flag=0;flag1=0;a=a+(n[i]-1);}
        }
        res[i]=a;
    }
    for (i=0;i<t;i++)
    {
        for (g=0;g<n[i];g++)
        {
            for (u=0;u<n[i];u++)
            {
                if (u==g) {cout<<res[i];}
                else {cout<<1;}
                cout<<" ";
            }
            cout<<endl;
        }
    }
}


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int t,i,g,a,u;
    cin>>t;
    int res[t],n[t];
    for (i=0;i<t;i++)
    {
        cin>>n[i];
        a=n[i];
        int flag=0; int flag1=0;
        while (flag==0)
        {
            for (g=2;g<=sqrt(a);g++)
            {
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {a++;flag1=0;}
            else {flag=1;a=a-(n[i]-1);}
            if (flag==1)
            {
                for (g=2;g<=sqrt(a);g++)
                if (a%g==0) {flag1=1;}
            }
            if ((flag1==0) and (a!=1)) {a++;flag=0;flag1=0;a=a+(n[i]-1);}
        }
        res[i]=a;
    }
    for (i=0;i<t;i++)
    {
        for (g=0;g<n[i];g++)
        {
            for (u=0;u<n[i];u++)
            {
                if (u==g) {cout<<res[i];}
                else {cout<<1;}
                cout<<" ";
            }
            cout<<endl;
        }
    }
}


#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int t,i,g,a,u;
    cin>>t;
    int res[t],n[t];
    for (i=0;i<t;i++)
    {
        cin>>n[i];
        a=n[i];
        int flag=0; int flag1=1;
        while ((flag==0) and (a<=1009))
        {
            for (g=2;g<=sqrt(a);g++)
            {
                if (a%g==0) {flag1=1;}
            }
            if (flag1==1) {a++;flag1=0;}
            else {flag=1;a=a-(n[i]-1);}
            if (flag==1)
            {
                for (g=2;g<=sqrt(a);g++)
                if (a%g==0) {flag1=1;}
            }
            if (flag1==0) {a++;flag=0;flag1=0;a=a+(n[i]-1);}
        }
        res[i]=a;
    }
    for (i=0;i<t;i++)
    {
        for (g=0;g<n[i];g++)
        {
            for (u=0;u<n[i];u++)
            {
                if (u==g) {cout<<res[i];}
                else {cout<<1;}
                cout<<" ";
            }
            cout<<endl;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    for(int i = 0; i < n;i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(i==j)
                arr[i].pb(1);
            else
                arr[i].pb(0);
        }
    }

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    if(n ==2){
        cout << 1 << " " << 1 << endl << 1 << " " << 1 <<endl;
        return;
    }

    for(int i = 0; i < n - 1; i++)
    {
        for(int j = 0; j < n - 1; j++)
        {
            arr[i].pb((j + 1) * 2);
            sum2 = (j+1)*2;

        }
        arr[i].pb(sum2 - 1);
        sum2 = 0;
    }
    int sum1 = 0;
    //for(int j = 0; j < n - 1; j++)
      //  arr[n-1].pb(pri(n*(j+1)));
    //for(int j = 0; j < n-1; j++)
      //  sum1 = arr[j][n-1];
    //
    //arr[n-1].pb(pri(sum1));
    for(int j = 0; j <n - 1; j++)
        arr[n-1].pb(1);
    arr[n-1].pb(4);

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    for(int i = 0; i < n;i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(i==j || i==(n-j-1))
            {
                arr[i].pb(1);
            }
            else
                arr[i].pb(0);
        }
    }
    if(n%2 == 1)
    {
        arr[n/2][n/2 + 1] = 1;
        arr[n/2+1][n/2] = 1;
    }

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    if(n ==2){
        cout << 1 << " " << 1 << endl << 1 << " " << 1 <<endl;
        return;
    }

    for(int i = 0; i < n - 1; i++)
    {
        for(int j = 0; j < n - 1; j++)
        {
            arr[i].pb((j + 2) * 2);
            sum2 = (j+1)*2;

        }
        arr[i].pb(1);
        sum2 = 0;
    }
    int sum1 = 0;
    //for(int j = 0; j < n - 1; j++)
      //  arr[n-1].pb(pri(n*(j+1)));
    //for(int j = 0; j < n-1; j++)
      //  sum1 = arr[j][n-1];
    //
    //arr[n-1].pb(pri(sum1));
    for(int j = 0; j <n - 1; j++)
        arr[n-1].pb(1);
    arr[n-1].pb(4);

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    	cin >> n;

	ll x = 0;
	for (ll j = 1; j <= 999999; j++) {
		if (!prime[j] && prime[(n - 1) + j]) {
			x = j;
			break;
		}
	}

	for (ll i = 0; i < n; i++) {
		for (ll j = 0; j < n; j++) {
			if (i == j) cout << x << " ";
			else cout << 1 << " ";
		}
		cout << '\n';
	}
}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    if(n ==2){
        cout << 1 << " " << 1 << endl << 1 << " " << 1 <<endl;
        return;
    }

    for(int i = 0; i < n - 1; i++)
    {
        for(int j = 0; j < n - 1; j++)
        {
            arr[i].pb((j + 1) * 2);
            sum2 = (j+1)*2;

        }
        arr[i].pb(1);
        sum2 = 0;
    }
    int sum1 = 0;
    //for(int j = 0; j < n - 1; j++)
      //  arr[n-1].pb(pri(n*(j+1)));
    //for(int j = 0; j < n-1; j++)
      //  sum1 = arr[j][n-1];
    //
    //arr[n-1].pb(pri(sum1));
    for(int j = 0; j <n - 1; j++)
        arr[n-1].pb(1);
    arr[n-1].pb(4);

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
       break;
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    int sum2 = 0;
    if(n ==2)
    {
        cout << 1 << " " << 2 << endl << 2 << " " << 1 <<endl;
        return;
    }

    vector<vector<int>> arr(n);
    for(int i = 0; i < n - 1; i++)
    {
        for(int j = 0; j < n - 1; j++)
        {
            arr[i].pb(j + 1);
            sum2 += j+1;

        }
        arr[i].pb(1);
        sum2 = 0;
    }
    int sum1 = 0;
    for(int j = 0; j < n - 1; j++)
        arr[n-1].pb(pri(n*(j+1)));
    for(int j = 0; j < n-1; j++)
        sum1 = arr[j][n-1];
    arr[n-1].pb(pri(sum1));

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    for(int i = 0; i < n;i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(i==j || i==(n-j-1))
                arr[i].pb(1);
            else
                arr[i].pb(0);
        }
    }

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;

#define rep(i,n) for (i = 0; i < n; ++i)
#define REP(i,k,n) for (i = k; i <= n; ++i)
#define REPR(i,k,n) for (i = k; i >= n; --i)

#define MP make_pair
#define pb push_back
#define INF 1000000000000000003
long long INFF = 1000000000000000005LL;

typedef unsigned long long ul;
#define ll long long int
#define maN 2e5
#define miN 0
template<typename T> void scan(T &x)
{
    x = 0;
    bool neg = 0;
    register T c = getchar();

    if (c == '-')
        neg = 1, c = getchar();

    while ((c < 48) || (c > 57))
        c = getchar();

    for ( ; c < 48||c > 57 ; c = getchar());

    for ( ; c > 47 && c < 58; c = getchar() )
        x= (x << 3) + ( x << 1 ) + ( c & 15 );

    if (neg) x *= -1;
}

template<typename T> void print(T n)
{
    bool neg = 0;

    if (n < 0)
        n *= -1, neg = 1;

    char snum[65];

    int i = 0;
    do
    {
        snum[i++] = n % 10 + '0';
        n /= 10;
    }

    while (n);
    --i;

    if (neg)
        putchar('-');

    while (i >= 0)
        putchar(snum[i--]);

    putchar('\n');
}

template<typename T, typename U>
static inline void amin(T &x, U y)
{
    if (y < x)
        x = y;
}

// call by reference is used in x
template<typename T, typename U>
static inline void amax(T &x, U y)
{
    if (x < y)
        x = y;
}

int nat(int n)
{
    int sum = 0;
    for(int i =1; i < n; i++)
        sum += i;
    return sum;

}

int pri(int n)
{

    int count = 0, prime = 1;
    while(n++){
   for(int loop = 2; loop < n ; loop++) {
      if((n % loop) == 0) {
         prime = 0;
      }
   }
   count++;
   if (prime == 1)
   {
       break;
   }
   prime = 1;
    }
    return count + 1;
}

void solve()
{

    int n;
    cin >> n;
    vector<vector<int>> arr(n);
    int sum2 = 0;
    for(int i = 0; i < n;i++)
    {
        for(int j = 0; j < n; j++)
        {
            if(i==j || i==(n-j-1))
            {
                if(n%2 == 1)
                {
                    if(i==n/2)
                        arr[i].pb(2);
                }
                arr[i].pb(1);
            }
            else
                arr[i].pb(0);
        }
    }

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }

}

int main()
{
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int n=1,a=0;
	cin>>n;
	rep(a,n)
		solve();

   	cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
	return 0;
}


// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
const int MAXN=1e7+5;
unordered_set<int>st;
void sieve(vector<int>&temp)
{

	vector<char> is_prime(MAXN+1, true);
	is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= MAXN; i++) {
    if (is_prime[i]) {
    	temp.pb(i);
    	st.insert(i);
        for (int j = i * i; j <= MAXN; j += i)
            is_prime[j] = false;
    }
}
}
int main()
{
	ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

	#ifndef ONLINE_JUDGE
	freopen("inputf.in","r",stdin);
	freopen("outputf.in","w",stdout);
	#endif

	int t;
	cin>>t;
	vector<int>primes;
	primes.clear();
	sieve(primes);
	while(t--)
	{
		int n;
		cin>>n;
		int grid[n][n];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				grid[i][j]=1;
		}
		//find the new value for col
		int val=n-1;
		int new_val_idx=upper_bound(primes.begin(),primes.end(),val)-primes.begin();
		int new_val;
		for(int i=new_val_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-val)==st.end())
			{
				new_val=primes[i]-val;
				break;
			}
		}
		//change the last col;
		//change the last row
		for(int i=0;i<n;i++)
		{
			grid[i][n-1]=new_val;
			grid[n-1][i]=new_val;
		}
		//change the value grid[n-1][n-1];
		int last_val=new_val*(n-1);
		int new_last_idx=upper_bound(primes.begin(),primes.end(),last_val)-primes.begin();
		int new_last;
		for(int i=new_last_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-last_val)==st.end())
			{
				new_last=primes[i]-last_val;
				break;
			}
		}
		grid[n-1][n-1]=new_last;

		//prinmt grid
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				cout<<grid[i][j]<<" ";
			cout<<endl;
		}

	}

}


// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
const int MAXN=1e8+5;
unordered_set<int>st;
void sieve(vector<int>&temp)
{

	vector<char> is_prime(MAXN+1, true);
	is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= MAXN; i++) {
    if (is_prime[i]) {
    	temp.emplace_back(i);
    	st.insert(i);
        for (int j = i * i; j <= MAXN; j += i)
            is_prime[j] = false;
    }
}
}
int main()
{
	ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

	#ifndef ONLINE_JUDGE
	freopen("inputf.in","r",stdin);
	freopen("outputf.in","w",stdout);
	#endif

	int t;
	cin>>t;
	vector<int>primes;
	primes.clear();
	sieve(primes);
	while(t--)
	{
		int n;
		cin>>n;
		int grid[n][n];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				grid[i][j]=1;
		}
		//find the new value for col
		int val=n-1;
		int new_val_idx=upper_bound(primes.begin(),primes.end(),val)-primes.begin();
		int new_val;
		for(int i=new_val_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-val)==st.end())
			{
				new_val=primes[i]-val;
				break;
			}
		}
		//change the last col;
		//change the last row
		for(int i=0;i<n;i++)
		{
			grid[i][n-1]=new_val;
			grid[n-1][i]=new_val;
		}
		//change the value grid[n-1][n-1];
		int last_val=new_val*(n-1);
		int new_last_idx=upper_bound(primes.begin(),primes.end(),last_val)-primes.begin();
		int new_last;
		for(int i=new_last_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-last_val)==st.end())
			{
				new_last=primes[i]-last_val;
				break;
			}
		}
		grid[n-1][n-1]=new_last;

		//prinmt grid
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				cout<<grid[i][j]<<" ";
			cout<<endl;
		}

	}

}


// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
const int MAXN=1e8+5;
unordered_set<int>st;
void sieve(vector<int>&temp)
{

	vector<char> is_prime(MAXN+1, true);
	is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= MAXN; i++) {
    if (is_prime[i]) {
    	temp.emplace_back(i);
    	st.insert(i);
        for (int j = i * i; j <= MAXN; j += i)
            is_prime[j] = false;
    }
}
}
int main()
{
	ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

	#ifndef ONLINE_JUDGE
	freopen("inputf.in","r",stdin);
	freopen("outputf.in","w",stdout);
	#endif

	int t;
	cin>>t;
	vector<int>primes;
	primes.clear();
	sieve(primes);
	while(t--)
	{
		int n;
		cin>>n;
		int grid[n][n];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				grid[i][j]=1;
		}
		//find the new value for col
		int val=n-1;
		int new_val_idx=upper_bound(primes.begin(),primes.end(),val)-primes.begin();
		int new_val;
		for(int i=new_val_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-val)==st.end())
			{
				new_val=primes[i]-val;
				break;
			}
		}
		//change the last col;
		//change the last row
		for(int i=0;i<n;i++)
		{
			grid[i][n-1]=new_val;
			grid[n-1][i]=new_val;
		}
		//change the value grid[n-1][n-1];
		int last_val=new_val*(n-1);
		int new_last_idx=upper_bound(primes.begin(),primes.end(),last_val)-primes.begin();
		int new_last;
		for(int i=new_last_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-last_val)==st.end())
			{
				new_last=primes[i]-last_val;
				break;
			}
		}
		grid[n-1][n-1]=new_last;

		//prinmt grid
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				printf("%d ",grid[i][j]);
			printf("\n");
		}

	}

}


// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
const int MAXN=1e6+5;
unordered_set<int>st;
void sieve(vector<int>&temp)
{

	vector<char> is_prime(MAXN+1, true);
	is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= MAXN; i++) {
    if (is_prime[i]) {
    	temp.pb(i);
    	st.insert(i);
        for (int j = i * i; j <= MAXN; j += i)
            is_prime[j] = false;
    }
}
}
int main()
{
	ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

	#ifndef ONLINE_JUDGE
	freopen("inputf.in","r",stdin);
	freopen("outputf.in","w",stdout);
	#endif

	int t;
	cin>>t;
	vector<int>primes;
	primes.clear();
	sieve(primes);
	while(t--)
	{
		int n;
		cin>>n;
		int grid[n][n];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				grid[i][j]=1;
		}
		//find the new value for col
		int val=n-1;
		int new_val_idx=upper_bound(primes.begin(),primes.end(),val)-primes.begin();
		int new_val;
		for(int i=new_val_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-val)==st.end())
			{
				new_val=primes[i]-val;
				break;
			}
		}
		//change the last col;
		//change the last row
		for(int i=0;i<n;i++)
		{
			grid[i][n-1]=new_val;
			grid[n-1][i]=new_val;
		}
		//change the value grid[n-1][n-1];
		int last_val=new_val*(n-1);
		int new_last_idx=upper_bound(primes.begin(),primes.end(),last_val)-primes.begin();
		int new_last;
		for(int i=new_last_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-last_val)==st.end())
			{
				new_last=primes[i]-last_val;
				break;
			}
		}
		grid[n-1][n-1]=new_last;

		//prinmt grid
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				cout<<grid[i][j]<<" ";
			cout<<endl;
		}

	}

}


// Created by Tanuj Jain
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef pair<int,int> pii;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const int INF = 0x3f3f3f3f;
int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}};
int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
const int MAXN=1e5+5;
unordered_set<int>st;
void sieve(vector<int>&temp)
{

	vector<char> is_prime(MAXN+1, true);
	is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= MAXN; i++) {
    if (is_prime[i]) {
    	temp.pb(i);
    	st.insert(i);
        for (int j = i * i; j <= MAXN; j += i)
            is_prime[j] = false;
    }
}
}
int main()
{
	ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

	#ifndef ONLINE_JUDGE
	freopen("inputf.in","r",stdin);
	freopen("outputf.in","w",stdout);
	#endif

	int t;
	cin>>t;
	vector<int>primes;
	primes.clear();
	sieve(primes);
	while(t--)
	{
		int n;
		cin>>n;
		int grid[n][n];
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				grid[i][j]=1;
		}
		//find the new value for col
		int val=n-1;
		int new_val_idx=upper_bound(primes.begin(),primes.end(),val)-primes.begin();
		int new_val;
		for(int i=new_val_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-val)==st.end())
			{
				new_val=primes[i]-val;
				break;
			}
		}
		//change the last col;
		//change the last row
		for(int i=0;i<n;i++)
		{
			grid[i][n-1]=new_val;
			grid[n-1][i]=new_val;
		}
		//change the value grid[n-1][n-1];
		int last_val=new_val*(n-1);
		int new_last_idx=upper_bound(primes.begin(),primes.end(),last_val)-primes.begin();
		int new_last;
		for(int i=new_last_idx;i<primes.size();i++)
		{
			if(st.find(primes[i]-last_val)==st.end())
			{
				new_last=primes[i]-last_val;
				break;
			}
		}
		grid[n-1][n-1]=new_last;

		//prinmt grid
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
				cout<<grid[i][j]<<" ";
			cout<<endl;
		}

	}

}


import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;

public class HarmoniousGraph {

	static class Pair implements Comparable<Pair> {
		int i, j;
		Pair(int i, int j) {
			this.i = i;
			this.j = j;
		}
		@Override
		public int compareTo(Pair arg0) {
			// TODO Auto-generated method stub
			return this.i - arg0.i;
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		Pair arr[] = new Pair[m];
		int parent[] =new int[n + 1];
		int size[] = new int[n + 1];
		for (int i = 0; i < n; i++) {
			parent[i] = i;
			size[i] = i;
		}
		for (int i = 0; i < m; i++) {
			arr[i] = new Pair(sc.nextInt(), sc.nextInt());
			union(parent, size, arr[i].i, arr[i].j);
			if (arr[i].i > arr[i].j) {
				int temp = arr[i].i;
				arr[i].i = arr[i].j;
				arr[i].j = temp;
			}
		}
		Arrays.sort(arr);
		Stack<Pair> st = new Stack<>();
		st.push(arr[0]);
		for (int i = 1; i < m; i++) {
			Pair top = st.peek();
	          if (top.j < arr[i].i)
	                st.push(arr[i]);
	            else if (top.j < arr[i].j)
	            {
	                top.j = arr[i].j;
	                st.pop();
	                st.push(top);
	            }
		}

		int count = 0;
		while (!st.isEmpty()) {
			Pair p = st.pop();
			int lroot = root(parent, p.i);
			for (int i = p.i + 1; i < p.j; i++) {
				int root = root(parent, i);
				if (root != lroot) {
					count++;
					if (size[root] > size[lroot]) {
						size[root] += size[lroot];
						parent[lroot] = root;
						lroot = root;
					}
					else {
						size[lroot] += size[root];
						parent[root] = lroot;
					}
				}
				if (size[lroot] == n) break;
			}
		}

		System.out.println(count);

	}
	static void union(int parent[], int size[], int i, int j) {
		int root1 = root(parent, i);
		int root2 = root(parent, j);
		if (root1 == root2) return;

		if (size[root1] > size[root2]) {
			size[root1] += size[root2];
			parent[root2] = root1;
		}
		else {
			size[root2] += size[root1];
			parent[root1] = root2;
		}
	}

	static int root(int parent[], int i) {
		while (parent[i] != i) {
			i = parent[i];
		}

		return i;
	}

}


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;

public class HarmoniousGraph {

	static class Pair implements Comparable<Pair> {
		int i, j;
		Pair(int i, int j) {
			this.i = i;
			this.j = j;
		}
		@Override
		public int compareTo(Pair arg0) {
			// TODO Auto-generated method stub
			return this.i - arg0.i;
		}
	}

	public static void main(String[] args) throws IOException {
		Reader br = new Reader();
		int n = br.nextInt();
		int m = br.nextInt();
		Pair arr[] = new Pair[m];
		int parent[] =new int[n + 1];
		int size[] = new int[n + 1];
		for (int i = 0; i < n; i++) {
			parent[i] = i;
			size[i] = i;
		}
		for (int i = 0; i < m; i++) {
			int f = br.nextInt();
			int s = br.nextInt();
			arr[i] = new Pair(f, s);
			union(parent, size, arr[i].i, arr[i].j);
			if (arr[i].i > arr[i].j) {
				int temp = arr[i].i;
				arr[i].i = arr[i].j;
				arr[i].j = temp;
			}
		}
		Arrays.sort(arr);
		Stack<Pair> st = new Stack<>();
		st.push(arr[0]);
		for (int i = 1; i < m; i++) {
			Pair top = st.peek();
	          if (top.j < arr[i].i)
	                st.push(arr[i]);
	            else if (top.j < arr[i].j)
	            {
	                top.j = arr[i].j;
	                st.pop();
	                st.push(top);
	            }
		}

		int count = 0;
		while (!st.isEmpty()) {
			Pair p = st.pop();
			int lroot = root(parent, p.i);
			for (int i = p.i + 1; i < p.j; i++) {
				int root = root(parent, i);
				if (root != lroot) {
					count++;
					if (size[root] > size[lroot]) {
						size[root] += size[lroot];
						parent[lroot] = root;
						lroot = root;
					}
					else {
						size[lroot] += size[root];
						parent[root] = lroot;
					}
				}
				if (size[lroot] == n) break;
			}
		}

		System.out.println(count);

	}
	static void union(int parent[], int size[], int i, int j) {
		int root1 = root(parent, i);
		int root2 = root(parent, j);
		if (root1 == root2) return;

		if (size[root1] > size[root2]) {
			size[root1] += size[root2];
			parent[root2] = root1;
		}
		else {
			size[root2] += size[root1];
			parent[root1] = root2;
		}
	}

	static int root(int parent[], int i) {
		while (parent[i] != i) {
			i = parent[i];
		}

		return i;
	}

    static class Reader
    {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer, bytesRead;

        public Reader()
        {
            din = new DataInputStream(System.in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[64]; // line length
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

        public int nextInt() throws IOException
        {
            int ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do
            {
                ret = ret * 10 + c - '0';
            }  while ((c = read()) >= '0' && c <= '9');

            if (neg)
                return -ret;
            return ret;
        }

        public long nextLong() throws IOException
        {
            long ret = 0;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();
            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');
            if (neg)
                return -ret;
            return ret;
        }

        public double nextDouble() throws IOException
        {
            double ret = 0, div = 1;
            byte c = read();
            while (c <= ' ')
                c = read();
            boolean neg = (c == '-');
            if (neg)
                c = read();

            do {
                ret = ret * 10 + c - '0';
            }
            while ((c = read()) >= '0' && c <= '9');

            if (c == '.')
            {
                while ((c = read()) >= '0' && c <= '9')
                {
                    ret += (c - '0') / (div *= 10);
                }
            }

            if (neg)
                return -ret;
            return ret;
        }

        private void fillBuffer() throws IOException
        {
            bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
            if (bytesRead == -1)
                buffer[0] = -1;
        }

        private byte read() throws IOException
        {
            if (bufferPointer == bytesRead)
                fillBuffer();
            return buffer[bufferPointer++];
        }

        public void close() throws IOException
        {
            if (din == null)
                return;
            din.close();
        }
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;

public class HarmoniousGraph {

	static class Pair implements Comparable<Pair> {
		int i, j;
		Pair(int i, int j) {
			this.i = i;
			this.j = j;
		}
		@Override
		public int compareTo(Pair arg0) {
			// TODO Auto-generated method stub
			return this.i - arg0.i;
		}
	}

	public static void main(String[] args) throws IOException {
		BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer str= new StringTokenizer(br.readLine());
		int n = Integer.parseInt(str.nextToken());
		int m = Integer.parseInt(str.nextToken());
		Pair arr[] = new Pair[m];
		int parent[] =new int[n + 1];
		int size[] = new int[n + 1];
		for (int i = 0; i < n; i++) {
			parent[i] = i;
			size[i] = i;
		}
		for (int i = 0; i < m; i++) {
			str = new StringTokenizer(br.readLine());
			int f = Integer.parseInt(str.nextToken());
			int s = Integer.parseInt(str.nextToken());
			arr[i] = new Pair(f, s);
			union(parent, size, arr[i].i, arr[i].j);
			if (arr[i].i > arr[i].j) {
				int temp = arr[i].i;
				arr[i].i = arr[i].j;
				arr[i].j = temp;
			}
		}
		Arrays.sort(arr);
		Stack<Pair> st = new Stack<>();
		st.push(arr[0]);
		for (int i = 1; i < m; i++) {
			Pair top = st.peek();
	          if (top.j < arr[i].i)
	                st.push(arr[i]);
	            else if (top.j < arr[i].j)
	            {
	                top.j = arr[i].j;
	                st.pop();
	                st.push(top);
	            }
		}

		int count = 0;
		while (!st.isEmpty()) {
			Pair p = st.pop();
			int lroot = root(parent, p.i);
			for (int i = p.i + 1; i < p.j; i++) {
				int root = root(parent, i);
				if (root != lroot) {
					count++;
					if (size[root] > size[lroot]) {
						size[root] += size[lroot];
						parent[lroot] = root;
						lroot = root;
					}
					else {
						size[lroot] += size[root];
						parent[root] = lroot;
					}
				}
				if (size[lroot] == n) break;
			}
		}

		System.out.println(count);

	}
	static void union(int parent[], int size[], int i, int j) {
		int root1 = root(parent, i);
		int root2 = root(parent, j);
		if (root1 == root2) return;

		if (size[root1] > size[root2]) {
			size[root1] += size[root2];
			parent[root2] = root1;
		}
		else {
			size[root2] += size[root1];
			parent[root1] = root2;
		}
	}

	static int root(int parent[], int i) {
		while (parent[i] != i) {
			i = parent[i];
		}

		return i;
	}

}


import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;

public class HarmoniousGraph {

	static class Pair implements Comparable<Pair> {
		int i, j;
		Pair(int i, int j) {
			this.i = i;
			this.j = j;
		}
		@Override
		public int compareTo(Pair arg0) {
			// TODO Auto-generated method stub
			return this.i - arg0.i;
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		Pair arr[] = new Pair[m];
		int parent[] =new int[n + 1];
		int size[] = new int[n + 1];
		for (int i = 0; i < n; i++) {
			parent[i] = i;
			size[i] = i;
		}
		for (int i = 0; i < m; i++) {
			arr[i] = new Pair(sc.nextInt(), sc.nextInt());
			union(parent, size, arr[i].i, arr[i].j);
			if (arr[i].i > arr[i].j) {
				int temp = arr[i].i;
				arr[i].i = arr[i].j;
				arr[i].j = temp;
			}
		}
		Arrays.sort(arr);
		Stack<Pair> st = new Stack<>();
		st.push(arr[0]);
		for (int i = 1; i < m; i++) {
			Pair top = st.peek();
	          if (top.j < arr[i].i)
	                st.push(arr[i]);
	            else if (top.j < arr[i].j)
	            {
	                top.j = arr[i].j;
	                st.pop();
	                st.push(top);
	            }
		}

		int count = 0;
		while (!st.isEmpty()) {
			Pair p = st.pop();
			int lroot = root(parent, p.i);
			for (int i = p.i + 1; i < p.j; i++) {
				int root = root(parent, i);
				if (root != lroot) {
					count++;
					if (size[root] > size[lroot]) {
						size[root] += size[lroot];
						parent[lroot] = root;
						lroot = root;
					}
					else {
						size[lroot] += size[root];
						parent[root] = lroot;
					}
				}
			}
		}

		System.out.println(count);

	}
	static void union(int parent[], int size[], int i, int j) {
		int root1 = root(parent, i);
		int root2 = root(parent, j);
		if (root1 == root2) return;

		if (size[root1] > size[root2]) {
			size[root1] += size[root2];
			parent[root2] = root1;
		}
		else {
			size[root2] += size[root1];
			parent[root1] = root2;
		}
	}

	static int root(int parent[], int i) {
		while (parent[i] != i) {
			i = parent[i];
		}

		return i;
	}

}


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

public class Ans {

    static int n;
    static int m;
    static ArrayList<Integer> adjList[];
    static TreeSet<Pair> res;
    static boolean visited[];
    static Pair maxMin;
    public static void dfs(int node) {
        visited[node] = true;
        for (Integer child : adjList[node]) {
            if (!visited[child]) {
                maxMin = new Pair(Math.min(maxMin.a, child), Math.max(maxMin.b, child));
                dfs(child);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        adjList = new ArrayList[n];
        visited = new boolean[n];
        res = new TreeSet<>();
        for (int i = 0; i < n; i++) {
            adjList[i] = new ArrayList<>();
        }
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            adjList[a].add(b);
            adjList[b].add(a);
        }
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                maxMin = new Pair(i, i);
                dfs(i);
                res.add(maxMin);
            }
        }
        int count = 0;
        for (Pair p : res) {
            Pair floor = res.lower(p);
            if (floor != null && floor.b > p.a) {
                count++;
            }
        }
        System.out.println(count);

    }
    static class Pair implements Comparable<Pair>{
        int a;
        int b;
        public Pair(int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public int compareTo(Pair o) {
            return this.a - o.a;
        }
    }
    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream System) throws FileNotFoundException {
            br = new BufferedReader(new InputStreamReader(System));
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

        public char nextChar() throws IOException {
            return next().charAt(0);
        }

        public Long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public boolean ready() throws IOException {
            return br.ready();
        }

        public void waitForInput() {
            for (long i = 0; i < 3e9; i++)
                ;
        }
    }
}


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

public class Ans {

    static int n;
    static int m;
    static ArrayList<Integer> adjList[];
    static ArrayList<Pair> res;
    static boolean visited[];
    static Pair maxMin;
    public static void dfs(int node) {
        visited[node] = true;
        for (Integer child : adjList[node]) {
            if (!visited[child]) {
                maxMin = new Pair(Math.min(maxMin.a, child), Math.max(maxMin.b, child));
                dfs(child);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        adjList = new ArrayList[n];
        visited = new boolean[n];
        res = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adjList[i] = new ArrayList<>();
        }
        for (int i = 0; i < m; i++) {
            int a = sc.nextInt() - 1;
            int b = sc.nextInt() - 1;
            adjList[a].add(b);
            adjList[b].add(a);
        }
        for (int i = 0; i < n; i++) {
            if (!visited[i]) {
                maxMin = new Pair(i, i);
                dfs(i);
                res.add(maxMin);
            }
        }
        int count = 0;
        int bigest = -1;
        for (Pair p : res) {
            if (p.a < bigest) {
                count++;
            }
            bigest = Math.max(p.b, bigest);
        }
        System.out.println(count);

    }
    static class Pair implements Comparable<Pair>{
        int a;
        int b;
        public Pair(int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public int compareTo(Pair o) {
            return this.a - o.a;
        }
    }
    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream System) throws FileNotFoundException {
            br = new BufferedReader(new InputStreamReader(System));
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

        public char nextChar() throws IOException {
            return next().charAt(0);
        }

        public Long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public boolean ready() throws IOException {
            return br.ready();
        }

        public void waitForInput() {
            for (long i = 0; i < 3e9; i++)
                ;
        }
    }
}


import java.util.*;

public class Main {
    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        UnionDisjoint ud = new UnionDisjoint(n + 1);
        for (int i = 0; i < m; i++) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            ud.union(from, to);
        }
        int current = 0;
        int cnt = 0;
        while (current <= n) {
            int set = ud.find(current);
            for (int i = current + 1; i <= set; i++) {
                if (ud.union(current, i)) {
                    cnt++;
                }
            }
            current = set + 1;
        }
        System.out.println(cnt);
    }

    static class UnionDisjoint {
        int[] set;

        UnionDisjoint(int n) {
            this.set = new int[n];
            for (int i = 0; i < n; i++) {
                set[i] = i;
            }
        }

        int find(int x) {
            if (x == set[x]) {
                return x;
            }
            set[x] = find(set[x]);
            return set[x];
        }

        boolean union(int x, int y) {
            if (find(x) == find(y)) {
                return false;
            }
            int xroot = find(x);
            int yroot = find(y);
            if (xroot < yroot) {
                set[xroot] = yroot;
            } else {
                set[yroot] = xroot;
            }
            return true;
        }

        boolean sameSet(int x, int y) {
            return find(x) == find(y);
        }
    }
}


import java.util.*;

public class Main {
    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        UnionDisjoint ud = new UnionDisjoint(n + 1);
        for (int i = 0; i < m; i++) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            ud.union(from, to);
        }
        int current = 0;
        int cnt = 0;
        while (current <= n) {
            int set = ud.find(current);
            for (int i = current + 1; i <= set; i++) {
                if (ud.union(current, i)) {
                    cnt++;
                }
            }
            if(ud.find(current) == set) {
                current = set + 1;
            }
        }
        System.out.println(cnt);
    }

    static class UnionDisjoint {
        int[] set;

        UnionDisjoint(int n) {
            this.set = new int[n];
            for (int i = 0; i < n; i++) {
                set[i] = i;
            }
        }

        int find(int x) {
            if (x == set[x]) {
                return x;
            }
            set[x] = find(set[x]);
            return set[x];
        }

        boolean union(int x, int y) {
            if (find(x) == find(y)) {
                return false;
            }
            int xroot = find(x);
            int yroot = find(y);
            if (xroot < yroot) {
                set[xroot] = yroot;
            } else {
                set[yroot] = xroot;
            }
            return true;
        }

        boolean sameSet(int x, int y) {
            return find(x) == find(y);
        }
    }
}


import java.util.*;

public class Main {

    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        DisjointUnionSets ud = new DisjointUnionSets(n + 1);
        for (int i = 0; i < m; i++) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            ud.union(from, to);
        }
        int current = 1;
        int cnt = 0;
        ud.shrinkWithMax();
        while (current < n + 1) {
            int set = ud.find(current);
            for (int i = current; i <= set; i++) {
                boolean united = ud.union(current, i);
                if (united) {
                    cnt++;
                }
            }
            current = set + 1;
        }
        System.out.println(cnt);
    }

    static class DisjointUnionSets {
        int[] rank, parent;
        int n;

        // Constructor
        public DisjointUnionSets(int n) {
            rank = new int[n];
            parent = new int[n];
            this.n = n;
            makeSet();
        }

        void makeSet() {
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }

        int find(int x) {
            if (parent[x] != x) {
                parent[x] = find(parent[x]);
            }

            return parent[x];
        }

        boolean union(int x, int y) {
            int xRoot = find(x), yRoot = find(y);

            if (xRoot == yRoot)
                return false;

            if (rank[xRoot] < rank[yRoot]) {

                parent[xRoot] = yRoot;
            } else if (rank[yRoot] < rank[xRoot]) {
                parent[yRoot] = xRoot;
            } else {
                parent[yRoot] = xRoot;
                rank[xRoot] = rank[xRoot] + 1;
            }
            return true;
        }

        boolean sameSet(int x, int y) {
            return find(x) == find(y);
        }

        public void shrinkWithMax() {
            Map<Integer, List<Integer>> components = new HashMap<>();
            Map<Integer, Integer> maxMap = new HashMap<>();
            for (int i = 0; i < parent.length; i++) {
                int setId = find(i);
                if (!components.containsKey(setId)) {
                    components.put(setId, new ArrayList<>());
                }
                components.get(setId).add(i);
                if (!maxMap.containsKey(setId)) {
                    maxMap.put(setId, 0);
                }
                maxMap.put(setId, Math.max(i, maxMap.get(setId)));
            }
            for (Integer setId : components.keySet()) {
                int max = maxMap.get(setId);
                for (Integer node : components.get(setId)) {
                    parent[node] = max;
                }
            }
        }
    }

}


import java.util.*;

public class Main {

    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        UnionDisjoint ud = new UnionDisjoint(n + 1);
        for (int i = 0; i < m; i++) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            ud.union(from, to);
        }
        int current = 1;
        int cnt = 0;
        ud.shrinkWithMax();
        while (current < n + 1) {
            int set = ud.findSet(current);
            for (int i = current; i <= set; i++) {
                boolean united = ud.union(current, i);
                if (united) {
                    cnt++;
                }
            }
            current = set + 1;
        }
        System.out.println(cnt);
    }

    static class UnionDisjoint {
        private int[] set;

        UnionDisjoint(int n) {
            this.set = new int[n];
            for (int i = 0; i < n; i++) {
                this.set[i] = i;
            }
        }

        public int findSet(int x) {
            if (set[x] != x) {
                set[x] = findSet(set[x]);
            }
            return set[x];
        }

        public boolean union(int x, int y) {
            if (sameSet(x, y)) {
                return false;
            }
            set[findSet(x)] = findSet(y);
            return true;
        }

        public boolean sameSet(int x, int y) {
            return findSet(x) == findSet(y);
        }

        public void shrinkWithMax() {
            Map<Integer, List<Integer>> components = new HashMap<>();
            Map<Integer, Integer> maxMap = new HashMap<>();
            for (int i = 0; i < set.length - 1; i++) {
                int setId = findSet(i);
                if (!components.containsKey(setId)) {
                    components.put(setId, new ArrayList<>());
                }
                components.get(setId).add(i);
                if (!maxMap.containsKey(setId)) {
                    maxMap.put(setId, 0);
                }
                maxMap.put(setId, Math.max(i, maxMap.get(setId)));
            }
            for (Integer setId : components.keySet()) {
                int max = maxMap.get(setId);
                for (Integer node : components.get(setId)) {
                    set[node] = max;
                }
            }
        }
    }

}


import java.util.*;

public class Main {

    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        UnionDisjoint ud = new UnionDisjoint(n + 1);
        for (int i = 0; i < m; i++) {
            int from = sc.nextInt();
            int to = sc.nextInt();
            ud.union(from, to);
        }
        int current = 1;
        int cnt = 0;
        ud.shrinkWithMax();
        while (current < n + 1) {
            int set = ud.findSet(current);
            for (int i = current; i <= set; i++) {
                boolean united = ud.union(current, i);
                if (united) {
                    cnt++;
                }
            }
            current = set + 1;
        }
        System.out.println(cnt);
    }

    static class UnionDisjoint {
        private int[] set;

        UnionDisjoint(int n) {
            this.set = new int[n];
            for (int i = 0; i < n; i++) {
                this.set[i] = i;
            }
        }

        public int findSet(int x) {
            if (set[x] != x) {
                set[x] = findSet(set[x]);
            }
            return set[x];
        }

        public boolean union(int x, int y) {
            if (sameSet(x, y)) {
                return false;
            }
            set[findSet(x)] = findSet(y);
            return true;
        }

        public boolean sameSet(int x, int y) {
            return findSet(x) == findSet(y);
        }

        public void shrinkWithMax() {
            Map<Integer, List<Integer>> components = new HashMap<>();
            Map<Integer, Integer> maxMap = new HashMap<>();
            for (int i = 0; i < set.length; i++) {
                int setId = findSet(i);
                if (!components.containsKey(setId)) {
                    components.put(setId, new ArrayList<>());
                }
                components.get(setId).add(i);
                if (!maxMap.containsKey(setId)) {
                    maxMap.put(setId, 0);
                }
                maxMap.put(setId, Math.max(i, maxMap.get(setId)));
            }
            for (Integer setId : components.keySet()) {
                int max = maxMap.get(setId);
                for (Integer node : components.get(setId)) {
                    set[node] = max;
                }
            }
        }
    }

}


import java.util.*;
import java.io.*;
import java.math.*;
public class a{
	static int [] parent,rank,min,max,size;
	static int find(int k){
		if(parent[k]!=k)
		  parent[k]=find(parent[k]);
		return parent[k];
	}
	static void merge(int a,int b){
		int x=find(a);
		int y=find(b);
		if(x==y)return;
		if(rank[x]>rank[y]){
			parent[y]=x;
			size[x]+=size[y];
			min[x]=Math.min(min[x],min[y]);
			max[x]=Math.max(max[x],max[y]);
		}
		else if(rank[y]>rank[x]){
			parent[x]=y;
			size[y]+=size[x];
			min[y]=Math.min(min[x],min[y]);
			max[y]=Math.max(max[x],max[y]);
		}
		else{
			parent[y]=x;
			size[x]+=size[y];
			min[x]=Math.min(min[x],min[y]);
			max[x]=Math.max(max[x],max[y]);
			rank[x]+=1;

		}
	}
	public static void main( String [] args) throws IOException{
		FastScanner sc=new FastScanner();
		int n=sc.nextInt();
		int m=sc.nextInt();
		parent=new int[n+1];
		rank=new int[n+1];
		min=new int[n+1];
		max=new int[n+1];
		size=new int[n+1];
		for(int i=1;i<=n;i++){
			parent[i]=i;
			rank[i]=0;
			min[i]=max[i]=i;
			size[i]=1;
		}

		for(int i=0;i<m;i++){
			int [] x=sc.nextIntArray(2);
			merge(x[0],x[1]);
		}
		Set<Integer> set=new HashSet<>();
		for(int i=1;i<=n;i++)set.add(find(i));

		int cnt=0;
		List<int[]> pair=new ArrayList<>();

		for(int x : set){
			int mn=min[x];
			int mx=max[x];
			pair.add(new int[]{mn,mx});
		}

		pair.sort((a,b)->a[0]-b[0]);
		int mn=pair.get(0)[0];
		int mx=pair.get(0)[1];
		for(int i=1;i<pair.size();i++){
			int l=pair.get(i)[0];
			int r=pair.get(i)[1];
			if(mx<l || mn>r)continue;
			cnt++;
			mx=Math.max(mx,r);
			mn=Math.min(mn,l);
		}
		System.out.println(cnt);

	}

  }

class FastScanner{
	 private int BUFFER_SIZE = 1 << 16;

	private  DataInputStream din;

	private  byte[] buffer;

	private int bufferPointer, bytesRead;

	public FastScanner() {
		din = new DataInputStream(System.in);
		buffer = new byte[BUFFER_SIZE];
		bufferPointer = bytesRead = 0;
	}

	public FastScanner( String file_name) throws IOException {
		din = new DataInputStream(new FileInputStream(file_name));
		buffer = new byte[BUFFER_SIZE];
		bufferPointer = bytesRead = 0;
    }

	public String readLine() throws IOException {
		 byte[] buf = new byte[64];
		int cnt = 0, c;
		while ((c = read()) != -1) {
			if (c == '\n')
				break;
			buf[cnt++] = (byte) c;
		}
		return new String(buf, 0, cnt);
	}

    public String next() throws IOException{

		byte c = read();
		while(Character.isWhitespace(c)){
			c = read();
		}

		 StringBuilder builder = new StringBuilder();
		builder.append((char)c);
		c = read();
		while(!Character.isWhitespace(c)){
			builder.append((char)c);
			c = read();
		}

		return builder.toString();
	}

	public int nextInt() throws IOException {
		int ret = 0;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();
		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');

		if (neg)
			return -ret;
		return ret;
	}

	public int[] nextIntArray( int n) throws IOException {
		 int arr[] = new int[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextInt();
		}
		return arr;
	}

	public long nextLong() throws IOException {
		long ret = 0;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();
		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');
		if (neg)
			return -ret;
		return ret;
	}

	public long[] nextLongArray( int n) throws IOException {
		 long arr[] = new long[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextLong();
		}
		return arr;
	}

	public char nextChar() throws IOException{
		byte c = read();
		while(Character.isWhitespace(c)){
			c = read();
		}
		return (char) c;
	}

	public double nextDouble() throws IOException {
		double ret = 0, div = 1;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();

		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');

		if (c == '.') {
			while ((c = read()) >= '0' && c <= '9') {
				ret += (c - '0') / (div *= 10);
			}
		}

		if (neg)
			return -ret;
		return ret;
    }

	public double[] nextDoubleArray( int n) throws IOException {
		 double arr[] = new double[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextDouble();
		}
		return arr;
	}

	private void fillBuffer() throws IOException {
		bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
		if (bytesRead == -1)
			buffer[0] = -1;
	}

	private byte read() throws IOException {
		if (bufferPointer == bytesRead)
			fillBuffer();
		return buffer[bufferPointer++];
	}

	public void close() throws IOException {
		if (din == null)
			return;
		din.close();
	}

}


import java.util.*;
import java.io.*;
import java.math.*;
public class a{
	static int [] parent,rank,min,max,size;
	static int find(int k){
		if(parent[k]!=k)
		  parent[k]=find(parent[k]);
		return parent[k];
	}
	static void merge(int a,int b){
		int x=find(a);
		int y=find(b);
		if(x==y)return;
		if(rank[x]>rank[y]){
			parent[y]=x;
			size[x]+=size[y];
			min[x]=Math.min(min[x],min[y]);
			max[x]=Math.max(max[x],max[y]);
		}
		else if(rank[y]>rank[x]){
			parent[x]=y;
			size[y]+=size[x];
			min[y]=Math.min(min[x],min[y]);
			max[y]=Math.max(max[x],max[y]);
		}
		else{
			parent[y]=x;
			size[x]+=size[y];
			min[x]=Math.min(min[x],min[y]);
			max[x]=Math.max(max[x],max[y]);
			rank[x]+=1;

		}
	}
	public static void main( String [] args) throws IOException{
		FastScanner sc=new FastScanner();
		int n=sc.nextInt();
		int m=sc.nextInt();
		parent=new int[n+1];
		rank=new int[n+1];
		min=new int[n+1];
		max=new int[n+1];
		size=new int[n+1];
		for(int i=1;i<=n;i++){
			parent[i]=i;
			rank[i]=0;
			min[i]=max[i]=i;
			size[i]=1;
		}

		for(int i=0;i<m;i++){
			int [] x=sc.nextIntArray(2);
			merge(x[0],x[1]);
		}
		Set<Integer> set=new HashSet<>();
		for(int i=1;i<=n;i++)set.add(find(i));

		int cnt=0;
		for(int x : set){
			int mn=min[x];
			int mx=max[x];
			int sz=size[x];
			if((mx-mn+1)!=sz){
				cnt++;
			}
		}
		if(cnt==0){
			System.out.println(0);
			return;
		}
		System.out.println(cnt-1);

	}

  }

class FastScanner{
	 private int BUFFER_SIZE = 1 << 16;

	private  DataInputStream din;

	private  byte[] buffer;

	private int bufferPointer, bytesRead;

	public FastScanner() {
		din = new DataInputStream(System.in);
		buffer = new byte[BUFFER_SIZE];
		bufferPointer = bytesRead = 0;
	}

	public FastScanner( String file_name) throws IOException {
		din = new DataInputStream(new FileInputStream(file_name));
		buffer = new byte[BUFFER_SIZE];
		bufferPointer = bytesRead = 0;
    }

	public String readLine() throws IOException {
		 byte[] buf = new byte[64];
		int cnt = 0, c;
		while ((c = read()) != -1) {
			if (c == '\n')
				break;
			buf[cnt++] = (byte) c;
		}
		return new String(buf, 0, cnt);
	}

    public String next() throws IOException{

		byte c = read();
		while(Character.isWhitespace(c)){
			c = read();
		}

		 StringBuilder builder = new StringBuilder();
		builder.append((char)c);
		c = read();
		while(!Character.isWhitespace(c)){
			builder.append((char)c);
			c = read();
		}

		return builder.toString();
	}

	public int nextInt() throws IOException {
		int ret = 0;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();
		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');

		if (neg)
			return -ret;
		return ret;
	}

	public int[] nextIntArray( int n) throws IOException {
		 int arr[] = new int[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextInt();
		}
		return arr;
	}

	public long nextLong() throws IOException {
		long ret = 0;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();
		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');
		if (neg)
			return -ret;
		return ret;
	}

	public long[] nextLongArray( int n) throws IOException {
		 long arr[] = new long[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextLong();
		}
		return arr;
	}

	public char nextChar() throws IOException{
		byte c = read();
		while(Character.isWhitespace(c)){
			c = read();
		}
		return (char) c;
	}

	public double nextDouble() throws IOException {
		double ret = 0, div = 1;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();

		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');

		if (c == '.') {
			while ((c = read()) >= '0' && c <= '9') {
				ret += (c - '0') / (div *= 10);
			}
		}

		if (neg)
			return -ret;
		return ret;
    }

	public double[] nextDoubleArray( int n) throws IOException {
		 double arr[] = new double[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextDouble();
		}
		return arr;
	}

	private void fillBuffer() throws IOException {
		bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
		if (bytesRead == -1)
			buffer[0] = -1;
	}

	private byte read() throws IOException {
		if (bufferPointer == bytesRead)
			fillBuffer();
		return buffer[bufferPointer++];
	}

	public void close() throws IOException {
		if (din == null)
			return;
		din.close();
	}

}


import java.util.*;
import java.io.*;
import java.math.*;
public class a{
	static int [] parent,rank,min,max,size;
	static int find(int k){
		if(parent[k]!=k)
		  parent[k]=find(parent[k]);
		return parent[k];
	}
	static void merge(int a,int b){
		int x=find(a);
		int y=find(b);
		if(x==y)return;
		if(rank[x]>rank[y]){
			parent[y]=x;
			size[x]+=size[y];
			min[x]=Math.min(min[x],min[y]);
			max[x]=Math.max(max[x],max[y]);
		}
		else if(rank[y]>rank[x]){
			parent[x]=y;
			size[y]+=size[x];
			min[y]=Math.min(min[x],min[y]);
			max[y]=Math.max(max[x],max[y]);
		}
		else{
			parent[y]=x;
			size[x]+=size[y];
			min[x]=Math.min(min[x],min[y]);
			max[x]=Math.max(max[x],max[y]);
			rank[x]+=1;

		}
	}
	public static void main( String [] args) throws IOException{
		FastScanner sc=new FastScanner();
		int n=sc.nextInt();
		int m=sc.nextInt();
		parent=new int[n+1];
		rank=new int[n+1];
		min=new int[n+1];
		max=new int[n+1];
		size=new int[n+1];
		for(int i=1;i<=n;i++){
			parent[i]=i;
			rank[i]=0;
			min[i]=max[i]=i;
			size[i]=1;
		}

		for(int i=0;i<m;i++){
			int [] x=sc.nextIntArray(2);
			merge(x[0],x[1]);
		}
		Set<Integer> set=new HashSet<>();
		for(int i=1;i<=n;i++)set.add(find(i));

		int cnt=0;
		List<int[]> pair=new ArrayList<>();

		for(int x : set){
			int mn=min[x];
			int mx=max[x];
			pair.add(new int[]{mn,mx});
		}

		pair.sort((a,b)->a[0]-b[0]);

		int last=0;
		for(int [] u : pair){
			if(u[0]<=last){
				cnt++;
			}
			last=Math.max(last,u[1]);
		}

		System.out.println(cnt);

	}

  }

class FastScanner{
	 private int BUFFER_SIZE = 1 << 16;

	private  DataInputStream din;

	private  byte[] buffer;

	private int bufferPointer, bytesRead;

	public FastScanner() {
		din = new DataInputStream(System.in);
		buffer = new byte[BUFFER_SIZE];
		bufferPointer = bytesRead = 0;
	}

	public FastScanner( String file_name) throws IOException {
		din = new DataInputStream(new FileInputStream(file_name));
		buffer = new byte[BUFFER_SIZE];
		bufferPointer = bytesRead = 0;
    }

	public String readLine() throws IOException {
		 byte[] buf = new byte[64];
		int cnt = 0, c;
		while ((c = read()) != -1) {
			if (c == '\n')
				break;
			buf[cnt++] = (byte) c;
		}
		return new String(buf, 0, cnt);
	}

    public String next() throws IOException{

		byte c = read();
		while(Character.isWhitespace(c)){
			c = read();
		}

		 StringBuilder builder = new StringBuilder();
		builder.append((char)c);
		c = read();
		while(!Character.isWhitespace(c)){
			builder.append((char)c);
			c = read();
		}

		return builder.toString();
	}

	public int nextInt() throws IOException {
		int ret = 0;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();
		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');

		if (neg)
			return -ret;
		return ret;
	}

	public int[] nextIntArray( int n) throws IOException {
		 int arr[] = new int[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextInt();
		}
		return arr;
	}

	public long nextLong() throws IOException {
		long ret = 0;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();
		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');
		if (neg)
			return -ret;
		return ret;
	}

	public long[] nextLongArray( int n) throws IOException {
		 long arr[] = new long[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextLong();
		}
		return arr;
	}

	public char nextChar() throws IOException{
		byte c = read();
		while(Character.isWhitespace(c)){
			c = read();
		}
		return (char) c;
	}

	public double nextDouble() throws IOException {
		double ret = 0, div = 1;
		byte c = read();
		while (c <= ' ')
			c = read();
		 boolean neg = (c == '-');
		if (neg)
			c = read();

		do {
			ret = ret * 10 + c - '0';
		} while ((c = read()) >= '0' && c <= '9');

		if (c == '.') {
			while ((c = read()) >= '0' && c <= '9') {
				ret += (c - '0') / (div *= 10);
			}
		}

		if (neg)
			return -ret;
		return ret;
    }

	public double[] nextDoubleArray( int n) throws IOException {
		 double arr[] = new double[n];
		for(int i = 0; i < n; i++){
			arr[i] = nextDouble();
		}
		return arr;
	}

	private void fillBuffer() throws IOException {
		bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
		if (bytesRead == -1)
			buffer[0] = -1;
	}

	private byte read() throws IOException {
		if (bufferPointer == bytesRead)
			fillBuffer();
		return buffer[bufferPointer++];
	}

	public void close() throws IOException {
		if (din == null)
			return;
		din.close();
	}

}


import java.util.*;

public class Main
{
    public static class DSU{
        int n;
        int[] prr;
        int[] max;
        int[] min;
        int tmph;
        DSU(int x)
        {
            n=x;
            prr=new int[n];
            max=new int[n];
            min=new int[n];
            for(int i=0;i<n;i++)
            {
                max[i]=min[i]=prr[i]=i;
            }
        }
        public int find(int x)
        {
            tmph=0; // use for calculating height
            while(prr[x]!=x)
            {
                x=prr[x];
                tmph++;
            }
            return x;
        }
        public boolean union(int x,int y)
        {
            int a=find(x);int h1=tmph;
            int b=find(y);int h2=tmph;
            if(a==b)
            return false;
            int m1=Math.min(min[a],min[b]);
            int m2=Math.max(max[a],max[b]);
            if(h1<=h2)
            {
                prr[a]=b;
                min[a]=m1;
                max[a]=m2;
            }
            else
            {
                prr[b]=a;
                min[b]=m1;
                max[b]=m2;
            }
            return true;
        }
    }
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int t=1;
		while(t-->0)
		{
		    int n=sc.nextInt();
		    DSU un=new DSU(n);
		    int m=sc.nextInt();
		    for(int i=0;i<m;i++)
		        un.union(sc.nextInt()-1,sc.nextInt()-1);
		    int p=0,i=0;
		    long ans=0;
		    while(i<n)
		    {
		        while(un.max[un.prr[p]]>i)
		        {
		            boolean x=un.union(p,i);
		            if(x)
		            ans++;
		            i++;
		        }
		        if(i<n)
		        {
		            p=i;
		            i++;
		        }
		    }
		    System.out.println(ans);
		}
	}
}


import java.util.*;

public class Main
{
    public static class DSU{
        int n;
        int[] prr;
        int[] max;
        int[] sz;
        int tmph;
        DSU(int x)
        {
            n=x;
            prr=new int[n];
            max=new int[n];
            sz=new int[n];
            for(int i=0;i<n;i++)
            {
                max[i]=prr[i]=i;
                sz[i]=1;
            }
        }
        public int find(int x)
        {
            tmph=0; // use for calculating height
            while(prr[x]!=x)
            {
                x=prr[x];
                tmph++;
            }
            return x;
        }
        public boolean union(int x,int y)
        {
            int a=find(x);int h1=tmph;
            int b=find(y);int h2=tmph;
            if(a==b)
            return false;
            int m2=Math.max(max[a],max[b]);
            if(sz[a]<=sz[b])
            {
                prr[a]=b;
                max[b]=m2;
                sz[b]+=sz[a];
            }
            else
            {
                prr[b]=a;
                max[a]=m2;
                sz[a]+=sz[b];
            }
            return true;
        }
    }
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int t=1;
		while(t-->0)
		{
		    int n=sc.nextInt();
		    DSU un=new DSU(n);
		    int m=sc.nextInt();
		    for(int i=0;i<m;i++)
		        un.union(sc.nextInt()-1,sc.nextInt()-1);
		    int p=0,i=0;
		    long ans=0;
		    for(i=0;i<n;i++)
		    {
		     //System.out.println(i+" "+un.max[un.find(i)]+" "+un.find(i));
		    }i=0;
		    while(i<n)
		    {
		        while(un.max[un.find(p)]>i)
		        {
		            boolean x=un.union(p,i);
		            if(x)
		            {
		                ans++;
		                //System.out.println(i+1+" "+un.max[un.prr[p]]+" "+ans);

		            }
		            i++;
		        }
		        if(i<n)
		        {
		            p=i;
		            i++;
		        }
		    }
		    System.out.println(ans);
		}
	}
}


import java.util.*;

public class Main
{
    public static class DSU{
        int n;
        int[] prr;
        int[] max;
        int[] min;
        int tmph;
        DSU(int x)
        {
            n=x;
            prr=new int[n];
            max=new int[n];
            min=new int[n];
            for(int i=0;i<n;i++)
            {
                max[i]=min[i]=prr[i]=i;
            }
        }
        public int find(int x)
        {
            tmph=0; // use for calculating height
            while(prr[x]!=x)
            {
                x=prr[x];
                tmph++;
            }
            return x;
        }
        public boolean union(int x,int y)
        {
            int a=find(x);int h1=tmph;
            int b=find(y);int h2=tmph;
            if(a==b)
            return false;
            int m1=Math.min(min[a],min[b]);
            int m2=Math.max(max[a],max[b]);
            if(h1<=h2)
            {
                prr[a]=b;
                min[b]=m1;
                max[b]=m2;
            }
            else
            {
                prr[b]=a;
                min[a]=m1;
                max[a]=m2;
            }
            return true;
        }
    }
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int t=1;
		while(t-->0)
		{
		    int n=sc.nextInt();
		    DSU un=new DSU(n);
		    int m=sc.nextInt();
		    for(int i=0;i<m;i++)
		        un.union(sc.nextInt()-1,sc.nextInt()-1);
		    int p=0,i=0;
		    long ans=0;
		    for(i=0;i<n;i++)
		    {
		     //System.out.println(i+" "+un.max[un.find(i)]+" "+un.find(i));
		    }i=0;
		    while(i<n)
		    {
		        while(un.max[un.find(p)]>i)
		        {
		            boolean x=un.union(p,i);
		            if(x)
		            {
		                ans++;
		                //System.out.println(i+1+" "+un.max[un.prr[p]]+" "+ans);

		            }
		            i++;
		        }
		        if(i<n)
		        {
		            p=i;
		            i++;
		        }
		    }
		    System.out.println(ans);
		}
	}
}