#include<iostream>
using namespace std;
int main()
{
int Z,I,M,L,i,n,check,point,a[10000];
n=1;
while(cin>>Z>>I>>M>>L)
{
if(Z==0&&I==0&&M==0&&L==0)break;
point=0;check=1;
while(check)
{
a[point++]=L;
L=(Z*L+I)%M;
for(i=0;i<point;i++)
if(a[i]==L)
{
check=0;break;
}
}
cout<<"Case "<<n++<<": "<<point-i<<endl;
}
}