#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MOD = 998244353,MX = 1e7;
const ll INF = 2e18;
ll gcd(ll x,ll y){return y == 0 ? x : gcd(y,x % y);}
ll ksm(ll x,ll b,ll p = MOD){ll ret = 1;while(b){if(b & 1)ret = ret * x % p;x = x * x % p;b >>= 1;}return ret;}
int pri[MX + 7],phi[MX + 7],tot = 0;bool mark[MX + 7];
int main(){
mark[0] = mark[1] = phi[1] = 1;
for(int i = 2;i <= MX;i++){
if(!mark[i]){
phi[i] = i - 1;
pri[++tot] = i;
}
for(int j = 1;j <= tot && i * pri[j] <= MX;j++){
mark[i * pri[j]] = true;
if(i % pri[j])phi[i * pri[j]] = phi[i] * phi[pri[j]];
else{
phi[i * pri[j]] = phi[i] * pri[j];
break;
}
}
}
int T;
cin >> T;
while(T--){
ll m,a,b,c,d,ans = 0;
cin >> m >> a >> b >> c >> d;
if(m > 10000000)exit(-1);
ll L = ksm(m,gcd(a,b),INF) + 1,R = ksm(m,gcd(c,d),INF);
if(a == 0 || b == 0)L = 1;
if(c == 0 || d == 0)R = 0;
ll n = R - L + 1;
for(int i = 1;i * i <= m;i++)
if(x % i == 0){
if(i & 1)ans = (ans + ksm(2,n / i) * phi[i]) % MOD;
if((m / i) & 1)ans = (ans + ksm(2,n / (m / i)) * phi[m / i]) % MOD;
}
cout << ans * ksm(m,MOD - 2) % MOD << '\n';
}
return 0;
}
// (m - 1) 2 ^ (n / m) + 2 ^ n / m