#!/usr/bin/perl -w

use v5.36;
use strict;
use experimental 'multidimensional';
use List::Util qw(reduce);

local $/ = "\n\n";

my (@queues, @ops, @divs, @ift, @iff, @steps);

while (<>) {
	my @lines = split /\n/;
	push @queues, [ $lines[1] =~ /\d+/g ];
	my ($op) = $lines[2] =~ /= (.*)/;
	$op =~ s/old/\$old/g;
	push @ops, $op;
	push @divs, $lines[3] =~ /(\d+)/;
	push @ift, $lines[4] =~ /(\d+)/;
	push @iff, $lines[5] =~ /(\d+)/;
}

my $mod = reduce { $a*$b } @divs;

for (1 .. 10_000) {
	for my $mk (0 .. $#queues) {
		my $q = $queues[$mk];
		while (my $old = shift @$q) {
			$steps[$mk]++;
			$old = eval $ops[$mk];
			$old %= $mod;
			if ($old % $divs[$mk]) {
				push @{ $queues[$iff[$mk]] }, $old;
			} else {
				push @{ $queues[$ift[$mk]] }, $old;
			}
		}
	}
}

@steps = sort { $b <=> $a } @steps;

say $steps[0] * $steps[1];

