1. 
/**
* FWP: Ausgewaehlte Probleme aus dem ACM (SS10)
*
* Method: Simulation
* Problem: 350 - Pseudo-RandomNumbers
* Accepted: 0.252
* @author Evgeni Pavlidis
*
*/
import java.io.*;
import java.util.*;

class Main {

private static Set<Integer> cycle = new HashSet<Integer>();

public static void main(String...args)
{
Scanner scanner = new Scanner(System.in);

int z,i,m,l, counter, caseNumber = 1;

while( (z = scanner.nextInt()) != 0)
{
i = scanner.nextInt();
m = scanner.nextInt();
l = scanner.nextInt();

cycle.clear();

counter = 0;
l = (z*l + i) % m;

do
{
cycle.add(l);
l = (z*l + i) % m;
counter++;

}while(!cycle.contains(l));

System.out.println("Case " + caseNumber++ + ": " + counter);
}
}
}