#include<bits/stdc++.h>
#define ll long long int
#define ld long double
#define pb push_back
#define fi first
#define se second
#define ios ios_base::sync_with_stdio(false)
using namespace std;
ll f(vector< vector<ll> > v, int idx)
{
int i;
ll area=0;
ll r=-1;
for(i=0;i<v.size();i++)
{
if(i==idx) continue;
if(v[i][0]>r)
{
area+=v[i][1]-v[i][0]+1;
r=v[i][1];
}
else if(v[i][0]==r)
{
area+=v[i][1]-v[i][0];
r=v[i][1];
}
else if(v[i][1]>r)
{
area+=v[i][1]-r;
r=v[i][1];
}
}
return area;
}
int main()
{
ios;
int t;
cin>>t;
int tc=1;
while(tc<=t)
{
ll n,l1,r1,a,b,c1,c2,m;
cin>>n>>l1>>r1>>a>>b>>c1>>c2>>m;
vector< vector<ll> > v,xy;
vector<ll> temp={l1,r1};
v.pb(temp);
xy.pb(temp);
int i;
ll x,y;
for(i=1;i<n;i++)
{
x=((((a%m)*(xy[i-1][0]%m))%m+((b%m)*(xy[i-1][1]%m))%m)%m+c1%m)%m;
y=((((a%m)*(xy[i-1][1]%m))%m+((b%m)*(xy[i-1][0]%m))%m)%m+c2%m)%m;
vector<ll> temp1={x,y};
xy.pb(temp1);
vector<ll> temp2={min(x,y),max(x,y)};
v.pb(temp2);
}
sort(v.begin(),v.end());
/*cout << "Generated Sets - \n";
for(i=0;i<v.size();i++) cout << v[i][0] << " " << v[i][1] << "\n";
cout << "---------------------\n";*/
ll ans=1000000000000000000L;
for(i=0;i<n;i++)
{
ans=min(ans,f(v,i));
}
cout << "Case #" << tc << ": " << ans << "\n";
tc++;
}
return 0;
}
// aC2+bC2+cC2+ab+bc
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4gCiNkZWZpbmUgbGwgbG9uZyBsb25nIGludAojZGVmaW5lIGxkIGxvbmcgZG91YmxlCiNkZWZpbmUgcGIgcHVzaF9iYWNrCiNkZWZpbmUgZmkgZmlyc3QKI2RlZmluZSBzZSBzZWNvbmQKI2RlZmluZSBpb3MgaW9zX2Jhc2U6OnN5bmN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