#include<iostream>

using namespace std;

int main()
{
int c = 0;
int Z, L, I, M;
while (cin >> Z >> I >> M >> L)
{
c++;
if(Z == L && L == I && I == M && M == 0)
{
return 0;
}
int i = 1;
int K, P;
I = I % M;
Z = Z % M;
K = L;
L = P = (Z * L + I) % M;
while (K != L)
{
L = (Z * L + I) % M;
if(L == P)
break;
i++;
}
cout << "Case " << c << ": " << i << endl;
}
return 0;
}

  

05-12 08:13