in reply to A mod2 Machine.

I played with the idea in base 10. Note that sometimes, the machine wins, but sometimes it does not:

#!/usr/bin/perl use warnings; use strict; use Test::More; use Benchmark qw(cmpthese); my %dispatch = ( simple => sub { my ($n, $d) = @_; 0 == $n % $d }, 1 => sub { 1 }, 2 => sub { shift =~ /[02468]$/ }, 3 => sub { my $n = shift; while (1 < length $n) { my $sum = 0; $sum += $_ for split //, $n; $n = $sum; } return grep $_ == $n, 0, 3, 6, 9; }, 4 => sub { my ($n) = shift =~ /(..)$/; 0 == $n % 4; }, 5 => sub { shift =~ /[05]$/ }, 7 => sub { my $n = shift; while (1 < length $n) { my $last = substr $n, -1, 1, q(); $n = abs($n - 2 * $last); } return (0 == $n or 7 == $n); }, 10 => sub { shift =~ /0$/ }, 11 => sub { my $n = shift; while (2 < length $n) { my $check = 0; my $i = 1; for (split //, $n) { $check += $i * $_; $i *= -1; } $n = abs $check; } return ($n == 0 or $n =~ /^(.)\1$/); }, ); my @divisors = sort { $a <=> $b } grep 'simple' ne $_, keys %dispatch; my @test_data = map int rand 1e12, 1 .. 1e7; for my $divisor (@divisors) { cmp_ok($dispatch{simple}->($_, $divisor), '==', $dispatch{$divisor}->($_)) for @test_data[0 .. 99]; } for my $divisor (@divisors) { print "\n$divisor\n"; my ($mogi, $magi) = (0, 0); cmpthese(1e7, { mod => sub { $dispatch{simple}->($test_data[$mogi++],$divi +sor) }, machine => sub { $dispatch{$divisor}->($test_data[$magi++])}, }); } done_testing();

The benchmark on my machine:

1 Rate mod machine mod 1949318/s -- -55% machine 4329004/s 122% -- 2 Rate machine mod machine 1428571/s -- -23% mod 1851852/s 30% -- 3 Rate machine mod machine 204666/s -- -89% mod 1848429/s 803% -- 4 Rate machine mod machine 974659/s -- -48% mod 1858736/s 91% -- 5 Rate mod machine mod 1855288/s -- -9% machine 2044990/s 10% -- 7 Rate machine mod machine 224517/s -- -88% mod 1845018/s 722% -- 10 Rate mod machine mod 1851852/s -- -39% machine 3058104/s 65% -- 11 Rate machine mod machine 209820/s -- -88% mod 1801802/s 759% --
لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ


Comment on Re: A mod2 Machine.
Select or Download Code