#include <iostream>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin>>t;
    while(t--){
        int n,m;
        cin>>n>>m;
        if(m == 1) cout<<n+1<<'\n';
        else if(m == 2) cout<<n<<'\n';
        else if(m == 3) cout<<1<<'\n';
        else cout<<0<<'\n';
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

①当a[n]等于n时,数组满足条件后有三个不同的数,分别是0,1,n,这种情况对应的数组数量只有1种;

②当a[n]为1到n-1之间的任一数时,数组满足条件后有两个不同的数,分别是0和a[n]所对应的数,这种情况对应的数组数量有n-1种;

③当a[n]为0时,数组满足条件后只有一个不同的数,为0,因此,这种情况所对应的数组数量有1种。

当m == 1时,①②③这三种情况均满足,因此输出n+1;

当m == 2时,只有①②满足,因此输出n;

当m == 3时,只有①满足,因此输出1;

当m为其他数时,以上三种情况均无法满足,输出0;