case = 1
while 1:
Z,I,M,L=list(map(int,input().split()))
firstL = L
if sum([Z,I,M,L]) == 0:
break
Ltotal = list()
for i in range(0,9999): #所有的Ltotal都變成1
Ltotal.append(1)
count = 0
while Ltotal[L] != 0: #判斷那個Ltotal的位置是否有被放東西過
Ltotal[L] = 0 #還沒被放過的數字讓他變成0,代表已放置
count += 1
L = (Z*L+I) % M
if firstL == L:
print(f"Case {case}: {count}")
else:
print(f"Case {case}: {count-1}")
case += 1