my @seen = (); my %power2 = (); my $power2 = 1; sub ispower2 { my $n = shift; while ($power2 <= $n) { $power2{$power2} = 1; $power2 *= 2; } return exists $power2{$n}; } sub other { my $n = shift; my $a = 1; while ($seen[$a] || not ispower2($a & $n)) { $a++; } $seen[$a]++; return $a; } foreach my $n (1..10_000) { my $a = other($n); print "$n $a\n"; }