1#!/usr/bin/perl -w 2 3use Test; 4use strict; 5 6my $count; 7 8BEGIN 9 { 10 $| = 1; 11 if ($^O eq 'os390') { print "1..0\n"; exit(0) } # test takes too long there 12 unshift @INC, '../lib'; # for running manually 13 my $location = $0; $location =~ s/mbi_rand.t//; 14 unshift @INC, $location; # to locate the testing files 15 chdir 't' if -d 't'; 16 $count = 128; 17 plan tests => $count*4; 18 } 19 20use Math::BigInt; 21my $c = 'Math::BigInt'; 22 23my $length = 128; 24 25# If you get a failure here, please re-run the test with the printed seed 26# value as input "perl t/mbi_rand.t seed" and send me the output 27 28my $seed = ($#ARGV == 0) ? $ARGV[0] : int(rand(1165537)); 29print "# seed: $seed\n"; srand($seed); 30 31my ($A,$B,$As,$Bs,$ADB,$AMB,$la,$lb); 32my $two = Math::BigInt->new(2); 33for (my $i = 0; $i < $count; $i++) 34 { 35 # length of A and B 36 $la = int(rand($length)+1); $lb = int(rand($length)+1); 37 $As = ''; $Bs = ''; 38 39 # we create the numbers from "patterns", e.g. get a random number and a 40 # random count and string them together. This means things like 41 # "100000999999999999911122222222" are much more likely. If we just strung 42 # together digits, we would end up with "1272398823211223" etc. It also means 43 # that we get more frequently equal numbers or other special cases. 44 while (length($As) < $la) { $As .= int(rand(100)) x int(rand(16)); } 45 while (length($Bs) < $lb) { $Bs .= int(rand(100)) x int(rand(16)); } 46 47 $As =~ s/^0+//; $Bs =~ s/^0+//; 48 $As = $As || '0'; $Bs = $Bs || '0'; 49 # print "# As $As\n# Bs $Bs\n"; 50 $A = $c->new($As); $B = $c->new($Bs); 51 # print "# A $A\n# B $B\n"; 52 if ($A->is_zero() || $B->is_zero()) 53 { 54 for (1..4) { ok (1,1); } next; 55 } 56 57 # check that int(A/B)*B + A % B == A holds for all inputs 58 59 # $X = ($A/$B)*$B + 2 * ($A % $B) - ($A % $B); 60 61 ($ADB,$AMB) = $A->copy()->bdiv($B); 62# print "# ($A / $B, $A % $B ) = $ADB $AMB\n"; 63 64 print "# seed $seed, ". join(' ',Math::BigInt::Calc->_base_len()),"\n". 65 "# tried $ADB * $B + $two*$AMB - $AMB\n" 66 unless ok ($ADB*$B+$two*$AMB-$AMB,$As); 67 print "# seed: $seed, \$ADB * \$B / \$B = ", $ADB * $B / $B, " != $ADB (\$B=$B)\n" 68 unless ok ($ADB*$B/$B,$ADB); 69 # swap 'em and try this, too 70 # $X = ($B/$A)*$A + $B % $A; 71 ($ADB,$AMB) = $B->copy()->bdiv($A); 72 #print "check: $ADB $AMB"; 73 print "# seed $seed, ". join(' ',Math::BigInt::Calc->_base_len()),"\n". 74 "# tried $ADB * $A + $two*$AMB - $AMB\n" 75 unless ok ($ADB*$A+$two*$AMB-$AMB,$Bs); 76# print " +$two * $AMB = ",$ADB * $A + $two * $AMB,"\n"; 77# print " -$AMB = ",$ADB * $A + $two * $AMB - $AMB,"\n"; 78 print "# seed $seed, \$ADB * \$A / \$A = ", $ADB * $A / $A, " != $ADB (\$A=$A)\n" 79 unless ok ($ADB*$A/$A,$ADB); 80 } 81 82