
import java.io.*;
import java.util.*;

// 1996 ACM North Central Region Programming Contest
// Solution to Problem Three, Copyright 2005, all rights reserved
// Mark Holliday
// Western Carolina University
// Department of Mathematics and Computer Science
class Rand
{
    private BufferedReader br;
    private int[] sequence;
    private int cycleLength;
    private int Z, I, M, L;
    
    public Rand()
    {
        try {
            br = new BufferedReader(new InputStreamReader(
                new FileInputStream(new File("C:\\holliday\\rand.in"))));
        } catch (Exception e) {e.printStackTrace();}
    }
    
    private void start()
    {
        int randCase = 1;
        while (anotherFourTuple())
        {
            System.out.println("Case " + randCase + ": " + findCycle());
            randCase++; 
        }
    }

    private boolean anotherFourTuple()
    {
        String xline = "";
        StringTokenizer line = new StringTokenizer("");
        try {
            xline = br.readLine();
            line = new StringTokenizer(xline);
        } catch (Exception e) {e.printStackTrace();}
        System.out.println(xline);
        System.out.println(line.countTokens() + ", " + line.hasMoreTokens());
        Z = Integer.parseInt(line.nextToken());
        I = Integer.parseInt(line.nextToken());
        M = Integer.parseInt(line.nextToken());
        L = Integer.parseInt(line.nextToken());
        if ((Z == 0) && (I == 0) && (M == 0) && (L == 0))
            return false;
        sequence = new int[M];
        sequence[0] = L;
        return true;
    }
    
    private int nextNum(int current)
    {
        return (Z * sequence[current] + I) % M;
    }

    private int findCycle()
    {
        int current = 0;
        boolean found = false;
        while (true) {
            sequence[current + 1] = nextNum(current);
            for (int i = 0; i < current + 1; i++)
                if (sequence[i] == sequence[current + 1])
                    return (current + 1) - i;   
            current++;
       }
    }
                
    public static void main(String[] args)
    {
        (new Rand()).start();
    }
}
			
