#include <stdio.h>
int main() {
int z,l,i,m;
int case_number = 1;
while(scanf("%d%d%d%d", &z, &i, &m, &l) == 4){
// Z,L,I --> const
if(z == 0 && l == 0 && i == 0 && m == 0)
break;
int abb = 0;
int board[10000] = {0};
while(board[l] == 0){
abb++;
board[l] = abb;
l = (z * l + i) % m;
}
printf("Case %d: %d\n", case_number++, abb - board[l] + 1);
}
return 0;
}