#include using namespace std; const int maxn = 65535; struct hash_tag { int key, num, next; }hash[maxn<<1]; int flag[maxn], idx, top; void insert(int n, int num) { int k = (n&65535); if (flag[k]!=idx) { flag[k] = idx; hash[k].key = n; hash[k].num = num; hash[k].next = -1; return; } while (hash[k].next != -1) { if (hash[k].key == n) return; k = hash[k].next; } hash[k].next = ++top; hash[top].key = n; hash[top].num = num; hash[top].next = -1; } int find(int n) { int k = (n&65535); if (flag[k]!=idx) { return -1; } while (k!=-1) { if (hash[k].key == n) return hash[k].num; k = hash[k].next; } return -1; } //map, set, hash_set, hash_map int main() { int Z = 0, I = 0, M = 0, L = 0; int t = 0; while (scanf("%d%d%d%d", &Z, &I, &M, &L)==4) { if (Z == 0&&I == 0&&M== 0&&L == 0) break; int count = 0, temp; top = maxn;idx++; t++; L = (Z*L+I)%M; while ((temp=find(L)) == -1) { insert(L, ++count); L = (Z*L+I)%M; } printf("Case %d: %d\n", t, count-temp+1); } return 0; }