Exemplo n.º 1
0
 public static function random($n, $s)
 {
     switch (BigInt::support()) {
         case 'gmp':
             $result = gmp_init(0);
             for ($i = 0; $i < $n; $i++) {
                 if (mt_rand(0, 1)) {
                     gmp_setbit($result, $i);
                 }
             }
             if ($s) {
                 gmp_setbit($result, $n - 1);
             }
             return $result;
         case 'big_int':
             $result = bi_rand($n);
             if ($s) {
                 $result = bi_set_bit($result, $n - 1);
             }
             return $result;
         case 'bcmath':
             bcscale(0);
             $t = BigInt::bcpow(2, $n);
             if ($s == 1) {
                 $m = bcdiv($t, 2);
                 $t = bcsub($m, 1);
             } else {
                 $m = 0;
                 $t = bcsub($t, 1);
             }
             $l = strlen($t);
             $n = (int) ($l / 9) + 1;
             $r = '';
             while ($n) {
                 $r .= substr('000000000' . mt_rand(0, 999999999), -9);
                 --$n;
             }
             $r = substr($r, 0, $l);
             while (bccomp($r, $t) == 1) {
                 $r = substr($r, 1, $l) . mt_rand(0, 9);
             }
             return bcadd($r, $m);
         case '':
         default:
             return BigInt::_random($n, $s);
     }
 }