} function bigint_powmod($x, $y, $m) { return gmp_powm($x, $y, $m); } } else { if (extension_loaded('big_int')) { function bigint_dec2num($dec)
/** * Generates random number wich bit length $bits_cnt, * using $random_generator as random generator function. * If is_set_higher_bit != false, then higer bit of result * will be set to 1. * * @param int $bits_cnt * @param string $rnd_generator * @return big_int resource * @access public */ function getRand($bits_cnt, $random_generator, $is_set_higher_bit = false) { $tmp = bi_rand($bits_cnt, $random_generator); return $is_set_higher_bit ? bi_set_bit($tmp, $bits_cnt - 1) : $tmp; }
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); } }
/* bitset functions */ echo '<h3>bitset functions</h3>' . "\n"; echo '<div style="text-align:right">'; echo '$a = [', bi_to_str($a, 2), "]<br/>\n"; echo '$b = [', bi_to_str($b, 2), "]<br/>\n"; $c = bi_or($a, $b); echo '$a or $b = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_xor($a, $b); echo '$a xor $b = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_and($a, $b); echo '$a and $b = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_andnot($a, $b); echo '$a andnot $b = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_set_bit($a, 0); echo 'set_bit($a, 0) = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_clr_bit($a, 0); echo 'clr_bit($a, 0) = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_inv_bit($a, 0); echo 'inv_bit($a, 0) = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_subint($a, 10, 20); echo 'subint($a, 10, 20) = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_rshift($a, 10); echo '$a >> 10 = [', bi_to_str($c, 2), "]<br/>\n"; $c = bi_lshift($a, 10); echo '$a << 10 = [', bi_to_str($c, 2), "]<br/>\n"; echo '</div>', "<br/>\n"; echo 'Hamming distance($a, $b) = ', bi_hamming_distance($a, $b), "<br/>\n"; echo 'bit_len($a) = ', bi_bit_len($a), "<br/>\n"; echo 'bit1_cnt($a) = ', bi_bit1_cnt($a), "<br/>\n";
/** returns a "good" prime $a with length $bit_len with resrtiction: $a - 1 != 0 (mod $e) */ function get_prime($bit_len) { return bi_next_prime(bi_set_bit(bi_rand($bit_len, 'microtime_generator'), $bit_len - 1)); }