#include <stdio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(void) {
long int z,i,m,l,times=1;
while(scanf("%ld%ld%ld%ld",&z,&i,&m,&l)!=EOF&&(z+i+m+l!=0)){
long int ans[10000],j,sum=0,temp;
for(j=0;j<10000;j++) ans[j]=0;
while(!ans[l]){
ans[l]=sum+1;
temp=(z*l+i);
l=temp%m;
sum++;
//printf("%ld\n",ans[l]);
}
printf("Case %ld: %ld\n",times++,(sum-ans[l]+1));
}
return 0;
}