$| = 1; sub can { my $avoid = shift; my $n = shift; my $p = 1; my $can = 0; while ($n) { while ($p & $avoid) { $p *= 2; } if ($n & 1) { $n--; $can += $p; } $n /= 2; $p *= 2; } return $can; } my %seen = (); sub other { my $n = shift; my $prev = shift; $seen{$prev} = 1; my $avoid = $n | $prev; my $k = 1; while (1) { my $can = can($avoid, $k); if (not exists $seen{$can}) { return $can; } $k++; } } my $a = 0; foreach my $n (1..100_000) { $a = other($n, $a); print "$n $a\n"; }