xref: /openbsd-src/gnu/usr.bin/perl/cpan/Math-BigInt-FastCalc/t/mbi_rand.t (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1#!/usr/bin/perl -w
2
3use Test::More;
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  unshift @INC, '../blib/arch';
14  my $location = $0; $location =~ s/mbi_rand.t//;
15  unshift @INC, $location; # to locate the testing files
16  chdir 't' if -d 't' && !$ENV{PERL_CORE};
17  $count = 128;
18  plan tests => $count*2;
19  }
20
21use Math::BigInt lib => 'FastCalc';
22my $c = 'Math::BigInt';
23
24my $length = 128;
25
26# If you get a failure here, please re-run the test with the printed seed
27# value as input: perl t/mbi_rand.t seed
28
29my $seed = ($#ARGV == 0) ? $ARGV[0] : int(rand(65537));
30print "# seed: $seed\n"; srand($seed);
31
32my ($A,$B,$As,$Bs,$ADB,$AMB,$la,$lb);
33my $two = Math::BigInt->new(2);
34for (my $i = 0; $i < $count; $i++)
35  {
36  # length of A and B
37  $la = int(rand($length)+1); $lb = int(rand($length)+1);
38  $As = ''; $Bs = '';
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.
43  while (length($As) < $la) { $As .= int(rand(100)) x int(rand(16)); }
44  while (length($Bs) < $lb) { $Bs .= int(rand(100)) x int(rand(16)); }
45  $As =~ s/^0+//; $Bs =~ s/^0+//;
46  $As = $As || '0'; $Bs = $Bs || '0';
47  # print "# As $As\n# Bs $Bs\n";
48  $A = $c->new($As); $B = $c->new($Bs);
49  # print "# A $A\n# B $B\n";
50  if ($A->is_zero() || $B->is_zero())
51    {
52    is (1,1); is (1,1); next;
53    }
54  # check that int(A/B)*B + A % B == A holds for all inputs
55  # $X = ($A/$B)*$B + 2 * ($A % $B) - ($A % $B);
56  ($ADB,$AMB) = $A->copy()->bdiv($B);
57  print "# ". join(' ',Math::BigInt::Calc->_base_len()),"\n"
58   unless is ($ADB*$B+$two*$AMB-$AMB,$As);
59  # swap 'em and try this, too
60  # $X = ($B/$A)*$A + $B % $A;
61  ($ADB,$AMB) = $B->copy()->bdiv($A);
62  print "# ". join(' ',Math::BigInt::Calc->_base_len()),"\n"
63   unless is ($ADB*$A+$two*$AMB-$AMB,$Bs);
64  }
65
66