public static function generateNthPrime(int $index) : \GMP { self::_validateNumber($index); $primeNumber = gmp_init(2); for ($counter = 0; $counter < $index; $counter++) { $primeNumber = gmp_nextprime($primeNumber); } return $primeNumber; }
public function getResult($num) { // init $prime = 1; for ($i = 0; $i < $num; $i++) { $prime = gmp_nextprime($prime); } return gmp_intval($prime); }
function all_primes() { global $argv; $input = intval($argv[1]); if ($input < 3) { die("Please input an integer larger than 2."); } $primes = array(); for ($i = 2; $i <= $input; $i = gmp_nextprime($i)) { array_push($primes, gmp_strval($i)); } return $primes; }
/** * Function for generating keys. Return array where * $array['module'] -> modulo N * $array['public'] -> public key E * $array['private'] -> private key D * * Public key pair is N and E * Private key pair is N and D * * @param integer $p * @param integer $q * @param boolean $show_debug * @return array */ public function generateKeys($p = null, $q = null, $show_debug = 0) { $p = !empty($p) ? $p : (int) gmp_strval(gmp_nextprime(mt_rand(0, 10000))); $q = !empty($q) ? $q : (int) gmp_strval(gmp_nextprime(mt_rand(0, 10000))); $n = bcmul($p, $q); //m (we need it to calculate D and E) $m = bcmul(bcsub($p, 1), bcsub($q, 1)); // Public key E $e = $this->findE($m); // Private key D $d = $this->extend($e, $m); $keys = array('module' => $n, 'public' => $e, 'private' => $d); if ($show_debug) { echo "P = {$p}<br />\n Q = {$q}<br />\n <b>N = {$n}</b> - modulo<br />\n M = {$m}<br />\n <b>E = {$e}</b> - public key<br />\n <b>D = {$d}</b> - private key<p>"; } return $keys; }
public static function next_prime($starting_value) { if (extension_loaded('gmp') && USE_EXT == 'GMP') { $result = gmp_strval(gmp_nextprime($starting_value)); return $result; } elseif (extension_loaded('bcmath') && USE_EXT == 'BCMATH') { if (bccomp($starting_value, 2) == -1) { return 2; } $result = bcmath_Utils::bcor(bcadd($starting_value, 1), 1); while (!self::is_prime($result)) { $result = bcadd($result, 2); } return $result; } else { throw new ErrorException("Please install BCMATH or GMP"); } }
public static function whoIsTheBestDev() { $foo = array('1.1862222222222', '1.9886666666667', '1.7618888888889', '1.6921111111111', '1.9014444444444', '1.4653333333333', '1.7618888888889', '1.6921111111111', '1.9014444444444'); $bar = ''; for ($i = 0; $i < count($foo); $i++) { $zbrah = 0; $lampe = 18; for ($j = 0; $j < 6; $j++) { $webcam = gmp_strval(gmp_nextprime($lampe)); $lampe += 4; $zbrah += $webcam; } $boubouleCircumLol = 40075; $boubouleDiameter = 6371 * pow(sqrt(2), 2); $cuisine = $boubouleCircumLol / $boubouleDiameter; $tourEiffel = $foo[$i]; $cookie = round($tourEiffel * $zbrah / $cuisine); $bar .= chr($cookie); } return $bar; }
/** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed, * give up and return false. * * @param optional Integer $min * @param optional Integer $max * @param optional Integer $timeout * @return Math_BigInteger * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($min = false, $max = false, $timeout = false) { $compare = $max->compare($min); if (!$compare) { return $min; } else { if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } } // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>. if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && function_exists('gmp_nextprime')) { // we don't rely on Math_BigInteger::random()'s min / max when gmp_nextprime() is being used since this function // does its own checks on $max / $min when gmp_nextprime() is used. When gmp_nextprime() is not used, however, // the same $max / $min checks are not performed. if ($min === false) { $min = new Math_BigInteger(0); } if ($max === false) { $max = new Math_BigInteger(0x7fffffff); } $x = $this->random($min, $max); $x->value = gmp_nextprime($x->value); if ($x->compare($max) <= 0) { return $x; } $x->value = gmp_nextprime($min->value); if ($x->compare($max) <= 0) { return $x; } return false; } static $one, $two; if (!isset($one)) { $one = new Math_BigInteger(1); $two = new Math_BigInteger(2); } $start = time(); $x = $this->random($min, $max); if ($x->equals($two)) { return $x; } $x->_make_odd(); if ($x->compare($max) > 0) { // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range if ($min->equals($max)) { return false; } $x = $min->copy(); $x->_make_odd(); } $initial_x = $x->copy(); while (true) { if ($timeout !== false && time() - $start > $timeout) { return false; } if ($x->isPrime()) { return $x; } $x = $x->add($two); if ($x->compare($max) > 0) { $x = $min->copy(); if ($x->equals($two)) { return $x; } $x->_make_odd(); } if ($x->equals($initial_x)) { return false; } } }
/** * Compiles an array initialization * * @param array $expression * @param CompilationContext $compilationContext * @return CompiledExpression */ public function compile($expression, CompilationContext $compilationContext) { /** * Resolves the symbol that expects the value */ if ($this->_expecting) { if ($this->_expectingVariable) { $symbolVariable = $this->_expectingVariable; $symbolVariable->initVariant($compilationContext); if ($symbolVariable->getType() != 'variable' && $symbolVariable->getType() != 'array') { throw new CompilerException("Cannot use variable type: " . $symbolVariable->getType() . " as an array", $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('array', $compilationContext, $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('array', $compilationContext, $expression); } /*+ * Mark the variable as an array */ $symbolVariable->setDynamicTypes('array'); $codePrinter = $compilationContext->codePrinter; /** * This calculates a prime number bigger than the current array size to possibly * reduce hash collisions when adding new members to the array */ $arrayLength = intval(count($expression['left']) * 1.25); if (!function_exists('gmp_nextprime')) { $codePrinter->output('array_init_size(' . $symbolVariable->getName() . ', ' . ($arrayLength + 1) . ');'); } else { $codePrinter->output('array_init_size(' . $symbolVariable->getName() . ', ' . gmp_strval(gmp_nextprime($arrayLength)) . ');'); } foreach ($expression['left'] as $item) { if (isset($item['key'])) { $key = null; $exprKey = new Expression($item['key']); $resolvedExprKey = $exprKey->compile($compilationContext); switch ($resolvedExprKey->getType()) { case 'string': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $codePrinter->output('add_assoc_long_ex(' . $symbolVariable->getName() . ', SS("' . $resolvedExprKey->getCode() . '"), ' . $resolvedExpr->getCode() . ');'); break; case 'double': $codePrinter->output('add_assoc_double_ex(' . $symbolVariable->getName() . ', SS("' . $resolvedExprKey->getCode() . '"), ' . $resolvedExpr->getCode() . ');'); break; case 'bool': $compilationContext->headersManager->add('kernel/array'); if ($resolvedExpr->getCode() == 'true') { $codePrinter->output('zephir_array_update_string(&' . $symbolVariable->getName() . ', SL("' . $resolvedExprKey->getCode() . '"), &ZEPHIR_GLOBAL(global_true), PH_COPY | PH_SEPARATE);'); } else { $codePrinter->output('zephir_array_update_string(&' . $symbolVariable->getName() . ', SL("' . $resolvedExprKey->getCode() . '"), &ZEPHIR_GLOBAL(global_false), PH_COPY | PH_SEPARATE);'); } break; case 'string': $codePrinter->output('add_assoc_stringl_ex(' . $symbolVariable->getName() . ', SS("' . $resolvedExprKey->getCode() . '"), SL("' . $resolvedExpr->getCode() . '"), 1);'); break; case 'null': $compilationContext->headersManager->add('kernel/array'); $codePrinter->output('zephir_array_update_string(&' . $symbolVariable->getName() . ', SL("' . $resolvedExprKey->getCode() . '"), &ZEPHIR_GLOBAL(global_null), PH_COPY | PH_SEPARATE);'); break; case 'array': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_string(&' . $symbolVariable->getName() . ', SL("' . $resolvedExprKey->getCode() . '"), &' . $valueVariable->getName() . ', PH_COPY | PH_SEPARATE);'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; case 'variable': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_string(&' . $symbolVariable->getName() . ', SL("' . $resolvedExprKey->getCode() . '"), &' . $valueVariable->getName() . ', PH_COPY | PH_SEPARATE);'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $resolvedExpr->getType(), $item['value']); } break; case 'int': case 'uint': case 'long': case 'ulong': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $codePrinter->output('add_index_long(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', ' . $resolvedExpr->getCode() . ');'); break; case 'bool': $compilationContext->headersManager->add('kernel/array'); $codePrinter->output('add_index_bool(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', ' . $resolvedExpr->getBooleanCode() . ');'); if ($resolvedExpr->getCode() == 'true') { $codePrinter->output('zephir_array_update_long(&' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', &ZEPHIR_GLOBAL(global_true), PH_COPY, "' . Compiler::getShortUserPath($expression['file']) . '", ' . $expression['line'] . ');'); } else { $codePrinter->output('zephir_array_update_long(&' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', &ZEPHIR_GLOBAL(global_false), PH_COPY, "' . Compiler::getShortUserPath($expression['file']) . '", ' . $expression['line'] . ');'); } break; case 'double': $codePrinter->output('add_index_double(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', ' . $resolvedExpr->getCode() . ');'); break; case 'null': $compilationContext->headersManager->add('kernel/array'); $codePrinter->output('zephir_array_update_long(&' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', &ZEPHIR_GLOBAL(global_null), PH_COPY, "' . Compiler::getShortUserPath($expression['file']) . '", ' . $expression['line'] . ');'); break; case 'string': $codePrinter->output('add_index_stringl(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', SL("' . $resolvedExpr->getCode() . '"), 1);'); break; case 'array': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_long(&' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', &' . $valueVariable->getName() . ', PH_COPY, "' . Compiler::getShortUserPath($expression['file']) . '", ' . $expression['line'] . ');'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; case 'variable': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_long(&' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', &' . $valueVariable->getName() . ', PH_COPY, "' . Compiler::getShortUserPath($expression['file']) . '", ' . $expression['line'] . ');'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $item['value']['type'], $item['value']); } break; case 'variable': $variableVariable = $compilationContext->symbolTable->getVariableForRead($resolvedExprKey->getCode(), $compilationContext, $item['key']); switch ($variableVariable->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $codePrinter->output('add_index_double(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', ' . $resolvedExpr->getCode() . ');'); break; case 'bool': $codePrinter->output('add_index_bool(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', ' . $resolvedExpr->getBooleanCode() . ');'); break; case 'double': $codePrinter->output('add_index_double(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', ' . $resolvedExpr->getCode() . ');'); break; case 'null': $codePrinter->output('add_index_null(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ');'); break; case 'string': $codePrinter->output('add_index_stringl(' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', SL("' . $resolvedExpr->getCode() . '"), 1);'); break; case 'variable': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_long(&' . $symbolVariable->getName() . ', ' . $resolvedExprKey->getCode() . ', &' . $valueVariable->getName() . ', PH_COPY, "' . Compiler::getShortUserPath($item['file']) . '", ' . $item['line'] . ');'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $item['value']['type'], $item['value']); } break; case 'string': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $codePrinter->output('add_assoc_long_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), ' . $resolvedExpr->getCode() . ');'); break; case 'double': $codePrinter->output('add_assoc_double_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), ' . $resolvedExpr->getCode() . ');'); break; case 'bool': $codePrinter->output('add_assoc_bool_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), ' . $resolvedExpr->getBooleanCode() . ');'); break; case 'string': $codePrinter->output('add_assoc_stringl_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . ') + 1, SL("' . $resolvedExpr->getCode() . '"), 1);'); break; case 'null': $codePrinter->output('add_assoc_null_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . ') + 1);'); break; case 'variable': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_string(&' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), &' . $valueVariable->getName() . ', PH_COPY);'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $resolvedExpr->getType(), $item['value']); } break; case 'variable': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'null': case 'bool': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_zval(&' . $symbolVariable->getName() . ', ' . $variableVariable->getName() . ', &' . $valueVariable->getName() . ', PH_COPY);'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; case 'variable': $compilationContext->headersManager->add('kernel/array'); $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $codePrinter->output('zephir_array_update_zval(&' . $symbolVariable->getName() . ', ' . $variableVariable->getName() . ', &' . $valueVariable->getName() . ', PH_COPY);'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $item['value']['type'], $item['value']); } break; default: throw new CompilerException("Cannot use variable type: " . $variableVariable->getType() . " as array index", $item['key']); } break; default: throw new CompilerException("Invalid key type: " . $resolvedExprKey->getType(), $item['key']); } } else { $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); $itemVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->headersManager->add('kernel/array'); $codePrinter->output('zephir_array_fast_append(' . $symbolVariable->getName() . ', ' . $itemVariable->getName() . ');'); if ($itemVariable->isTemporal()) { $itemVariable->setIdle(true); } } } return new CompiledExpression('array', $symbolVariable->getRealName(), $expression); }
<?php /** * Summation of primes * * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. * Find the sum of all the primes below two million. */ $primes_below = 2000000; $primes_sum = 0; $i = 0; while ($i < $primes_below) { $i = gmp_intval(gmp_nextprime($i)); if ($i < $primes_below) { $primes_sum += $i; } } echo $primes_sum;
<?php $n = gmp_nextprime(-1); var_dump(gmp_strval($n)); $n = gmp_nextprime(0); var_dump(gmp_strval($n)); $n = gmp_nextprime(-1000); var_dump(gmp_strval($n)); $n = gmp_nextprime(1000); var_dump(gmp_strval($n)); $n = gmp_nextprime(100000); var_dump(gmp_strval($n)); $n = gmp_nextprime(array()); var_dump(gmp_strval($n)); $n = gmp_nextprime(""); var_dump(gmp_strval($n)); $n = gmp_nextprime(new stdclass()); var_dump(gmp_strval($n)); echo "Done\n";
/** * Generate a random prime number between a range * * If there's not a prime within the given range, false will be returned. * If more than $timeout seconds have elapsed, give up and return false. * * @param \phpseclib\Math\BigInteger $min * @param \phpseclib\Math\BigInteger $max * @param int $timeout * @return Math_BigInteger|false * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ static function randomRangePrime(BigInteger $min, BigInteger $max, $timeout = false) { $compare = $max->compare($min); if (!$compare) { return $min->isPrime() ? $min : false; } elseif ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } static $one, $two; if (!isset($one)) { $one = new static(1); $two = new static(2); } $start = time(); $x = self::random($min, $max); // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>. if (MATH_BIGINTEGER_MODE == self::MODE_GMP && extension_loaded('gmp')) { $p = new static(); $p->value = gmp_nextprime($x->value); if ($p->compare($max) <= 0) { return $p; } if (!$min->equals($x)) { $x = $x->subtract($one); } return self::randomPrime($min, $x); } if ($x->equals($two)) { return $x; } $x->_make_odd(); if ($x->compare($max) > 0) { // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range if ($min->equals($max)) { return false; } $x = clone $min; $x->_make_odd(); } $initial_x = clone $x; while (true) { if ($timeout !== false && time() - $start > $timeout) { return false; } if ($x->isPrime()) { return $x; } $x = $x->add($two); if ($x->compare($max) > 0) { $x = clone $min; if ($x->equals($two)) { return $x; } $x->_make_odd(); } if ($x->equals($initial_x)) { return false; } } }
public static function nextPrimeBetween($lo = self::LO_MAX, $hi = self::HI_MAX) { # Sanitize PHP Bullfrogs $lo = preg_replace("[^0-9]", '', "{$lo}"); $hi = preg_replace("[^0-9]", '', "{$hi}"); if ($lo == $hi) { return $lo; } else { if ($lo < $hi || $hi > $lo) { # Swappish Sanity $t = $lo; $lo = $hi; $hi = $t; } } # Still unused :) if ($lo < self::LO_MAX || $hi > self::HI_MAX) { # Your prime is not in range! return self::NO_NO_NOOOO; } # Check how cool you are switch (GWF_Random::rand(0, 4)) { case 0: return self::NO_PRIME; case 1: return self::NO_CLUE; # case 2: return self::NO_NEO; # case 2: return self::NO_NEO; case 3: return self::NO_NO_NO; case 4: case 2: # Good Enough :) $the_value = '1'; while ($the_value < self::HI_MAX) { $the_value = gmp_strval(gmp_nextprime(gmp_random(2))); } return $the_value; } }
public function generatePrimeNumber($length) { $bin_random = '1' . $this->binRandom($length - 2) . '1'; $dec_random = $this->bin2dec($bin_random); return gmp_nextprime($dec_random); }
$divisors_needed = 500; $number_found = false; $triangle_number = 0; $i = 1; while (!$number_found) { $triangle_number += $i; $current_number = $triangle_number; $prime = 2; $prime_count = 0; $divisors = 0; while ($prime <= $current_number) { if ($current_number % $prime == 0) { $prime_count++; $current_number = $current_number / $prime; } else { if ($divisors != 0) { $divisors = $divisors * ($prime_count + 1); } else { $divisors = $prime_count + 1; } if ($divisors * 2 > $divisors_needed) { $number_found = true; } $prime = gmp_strval(gmp_nextprime($prime)); $prime_count = 0; } } $divisors = $divisors * 2; $i++; } echo $triangle_number . PHP_EOL;
<?php //print the first 1000 primes $prime = array(1, 2); while (count($prime) < 1000) { $num = gmp_nextprime(end($prime)); array_push($prime, gmp_strval($num)); } $i = 1; foreach ($prime as $item) { echo $i . " : " . $item . " <br>"; $i++; }
echo gmp_legendre("2", "3") . "\n"; // gmp_mod $mod = gmp_mod("8", "3"); echo gmp_strval($mod) . "\n"; // gmp_mul $mul = gmp_mul("12345678", "2000"); echo gmp_strval($mul) . "\n"; // gmp_neg $neg1 = gmp_neg("1"); echo gmp_strval($neg1) . "\n"; $neg2 = gmp_neg("-1"); echo gmp_strval($neg2) . "\n"; // gmp_nextprime $prime1 = gmp_nextprime(10); // next prime number greater than 10 $prime2 = gmp_nextprime(-1000); // next prime number greater than -1000 echo gmp_strval($prime1) . "\n"; echo gmp_strval($prime2) . "\n"; // gmp_or $or1 = gmp_or("0xfffffff2", "4"); echo gmp_strval($or1, 16) . "\n"; $or2 = gmp_or("0xfffffff2", "2"); echo gmp_strval($or2, 16) . "\n"; // gmp_perfect_square var_dump(gmp_perfect_square("9")); // 3 * 3, perfect square var_dump(gmp_perfect_square("7")); // not a perfect square // 1234567890 * 1234567890, perfect square var_dump(gmp_perfect_square("1524157875019052100"));
<?php /** * 10001st prime * * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. * What is the 10 001st prime number? */ $prime = 10001; $last_prime = 0; for ($i = 0; $i < $prime; $i++) { $last_prime = gmp_strval(gmp_nextprime($last_prime)); } echo $last_prime;
<?php /** * Largest prime factor * * The prime factors of 13195 are 5, 7, 13 and 29. * What is the largest prime factor of the number 600851475143 ? */ $largest_of = 13195; //600851475143; $largest_prime_factor = 0; $i = 0; while ($i < $largest_of) { $i = gmp_strval(gmp_nextprime($i)); if (fmod($largest_of, $i) == 0) { $largest_prime_factor = $i; } } echo $largest_prime_factor;
/** * Generates prime number with length $bits_cnt * * @param int $bits_cnt */ public function getPrime($bits_cnt) { $bytes_n = intval($bits_cnt / 8); do { $str = ''; $str = openssl_random_pseudo_bytes($bytes_n); $num = $this->_bin2int($str); $num = gmp_strval(gmp_nextprime($num)); } while ($this->_bitLen($num) != $bits_cnt); return $num; }
<?php $address = '127.0.0.1'; $port = 1337; echo "Creating a socket...\n"; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; } else { echo "OK.\n"; } echo "Connecting to {$address} : {$port}...\n"; $result = socket_connect($socket, $address, $port); if ($result === false) { echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n"; } else { echo "OK.\n"; } while ($out = socket_read($socket, 2048)) { echo "Read {$out} \n"; if (preg_match('/prime number after (\\d+)/i', $out, $m)) { $gmp_next_prime = gmp_nextprime($m[1]); $next_prime = gmp_strval($gmp_next_prime); echo "Writing {$next_prime}\n"; socket_write($socket, $next_prime, strlen($next_prime)); } sleep(0.5); } socket_close($socket);
/** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. If more than $timeout seconds have elapsed, * give up and return false. * * @param optional Integer $min * @param optional Integer $max * @param optional Integer $timeout * @return Math_BigInteger * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($min = false, $max = false, $timeout = false) { // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>. if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && function_exists('gmp_nextprime')) { // we don't rely on Math_BigInteger::random()'s min / max when gmp_nextprime() is being used since this function // does its own checks on $max / $min when gmp_nextprime() is used. When gmp_nextprime() is not used, however, // the same $max / $min checks are not performed. if ($min === false) { $min = new Math_BigInteger(0); } if ($max === false) { $max = new Math_BigInteger(0x7fffffff); } $compare = $max->compare($min); if (!$compare) { return $min; } else { if ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } } $x = $this->random($min, $max); $x->value = gmp_nextprime($x->value); if ($x->compare($max) <= 0) { return $x; } $x->value = gmp_nextprime($min->value); if ($x->compare($max) <= 0) { return $x; } return false; } $repeat1 = $repeat2 = array(); $one = new Math_BigInteger(1); $two = new Math_BigInteger(2); $start = time(); do { if ($timeout !== false && time() - $start > $timeout) { return false; } $x = $this->random($min, $max); if ($x->equals($two)) { return $x; } // make the number odd switch (MATH_BIGINTEGER_MODE) { case MATH_BIGINTEGER_MODE_GMP: gmp_setbit($x->value, 0); break; case MATH_BIGINTEGER_MODE_BCMATH: if ($x->value[strlen($x->value) - 1] % 2 == 0) { $x = $x->add($one); } break; default: $x->value[0] |= 1; } // if we've seen this number twice before, assume there are no prime numbers within the given range if (in_array($x->value, $repeat1)) { if (in_array($x->value, $repeat2)) { return false; } else { $repeat2[] = $x->value; } } else { $repeat1[] = $x->value; } } while (!$x->isPrime()); return $x; }
/** * Compiles an array initialization * * @param array $expression * @param CompilationContext $compilationContext * @return CompiledExpression */ public function compile($expression, CompilationContext $compilationContext) { /** * Resolves the symbol that expects the value */ if ($this->_expecting) { if ($this->_expectingVariable) { $symbolVariable = $this->_expectingVariable; $symbolVariable->initVariant($compilationContext); if ($symbolVariable->getType() != 'variable' && $symbolVariable->getType() != 'array') { throw new CompilerException("Cannot use variable type: " . $symbolVariable->getType() . " as an array", $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('array', $compilationContext, $expression); } } else { $symbolVariable = $compilationContext->symbolTable->getTempVariableForWrite('array', $compilationContext, $expression); } /*+ * Mark the variable as an array */ $symbolVariable->setDynamicTypes('array'); $codePrinter = $compilationContext->codePrinter; if (!isset($expression['left'])) { return new CompiledExpression('array', $symbolVariable->getRealName(), $expression); } $compilationContext->headersManager->add('kernel/array'); /** * This calculates a prime number bigger than the current array size to possibly * reduce hash collisions when adding new members to the array */ $arrayLength = count($expression['left']); if ($arrayLength >= 33 && function_exists('gmp_nextprime')) { $arrayLength = gmp_strval(gmp_nextprime($arrayLength - 1)); } $compilationContext->backend->initArray($symbolVariable, $compilationContext, $arrayLength > 0 ? $arrayLength : null); foreach ($expression['left'] as $item) { if (isset($item['key'])) { $key = null; $exprKey = new Expression($item['key']); $resolvedExprKey = $exprKey->compile($compilationContext); switch ($resolvedExprKey->getType()) { case 'string': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': case 'double': $compilationContext->backend->addArrayEntry($symbolVariable, $resolvedExprKey, $resolvedExpr, $compilationContext); break; case 'bool': $compilationContext->headersManager->add('kernel/array'); if ($resolvedExpr->getCode() == 'true') { $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, 'true', $compilationContext, 'PH_COPY | PH_SEPARATE'); } else { $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, 'false', $compilationContext, 'PH_COPY | PH_SEPARATE'); } break; case 'string': $compilationContext->backend->addArrayEntry($symbolVariable, $resolvedExprKey, $resolvedExpr, $compilationContext); break; case 'null': $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, 'null', $compilationContext, 'PH_COPY | PH_SEPARATE'); break; case 'array': case 'variable': $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, $valueVariable, $compilationContext, 'PH_COPY | PH_SEPARATE'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $resolvedExpr->getType(), $item['value']); } break; case 'int': case 'uint': case 'long': case 'ulong': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': case 'double': case 'string': $compilationContext->backend->addArrayEntry($symbolVariable, $resolvedExprKey, $resolvedExpr, $compilationContext); break; case 'bool': if ($resolvedExpr->getCode() == 'true') { $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, 'true', $compilationContext, 'PH_COPY'); } else { $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, 'false', $compilationContext, 'PH_COPY'); } break; case 'null': $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, 'null', $compilationContext, 'PH_COPY'); break; case 'array': case 'variable': $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, $valueVariable, $compilationContext, 'PH_COPY'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $item['value']['type'], $item['value']); } break; case 'variable': $variableVariable = $compilationContext->symbolTable->getVariableForRead($resolvedExprKey->getCode(), $compilationContext, $item['key']); switch ($variableVariable->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': case 'bool': case 'double': case 'null': case 'string': $compilationContext->backend->addArrayEntry($symbolVariable, $resolvedExprKey, $resolvedExpr, $compilationContext); break; case 'variable': $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, $valueVariable, $compilationContext, 'PH_COPY'); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $item['value']['type'], $item['value']); } break; case 'string': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'int': case 'uint': case 'long': case 'ulong': $codePrinter->output('add_assoc_long_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), ' . $resolvedExpr->getCode() . ');'); break; case 'double': $codePrinter->output('add_assoc_double_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), ' . $resolvedExpr->getCode() . ');'); break; case 'bool': $codePrinter->output('add_assoc_bool_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . '), ' . $resolvedExpr->getBooleanCode() . ');'); break; case 'string': $compilationContext->backend->addArrayEntry($symbolVariable, $resolvedExprKey, $resolvedExpr, $compilationContext); break; case 'null': $codePrinter->output('add_assoc_null_ex(' . $symbolVariable->getName() . ', Z_STRVAL_P(' . $resolvedExprKey->getCode() . '), Z_STRLEN_P(' . $item['key']['value'] . ') + 1);'); break; case 'variable': $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->backend->updateArray($symbolVariable, $resolvedExprKey, $resolvedExpr, $compilationContext); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $resolvedExpr->getType(), $item['value']); } break; case 'variable': $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); switch ($resolvedExpr->getType()) { case 'null': case 'bool': $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->backend->updateArray($symbolVariable, $variableVariable, $valueVariable, $compilationContext); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; case 'variable': $valueVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $compilationContext->backend->updateArray($symbolVariable, $variableVariable, $valueVariable, $compilationContext); if ($valueVariable->isTemporal()) { $valueVariable->setIdle(true); } break; default: throw new CompilerException("Invalid value type: " . $item['value']['type'], $item['value']); } break; default: throw new CompilerException("Cannot use variable type: " . $variableVariable->getType() . " as array index", $item['key']); } break; default: throw new CompilerException("Invalid key type: " . $resolvedExprKey->getType(), $item['key']); } } else { $expr = new Expression($item['value']); $resolvedExpr = $expr->compile($compilationContext); $itemVariable = $this->getArrayValue($resolvedExpr, $compilationContext); $symbol = $compilationContext->backend->getVariableCode($symbolVariable); $item = $compilationContext->backend->resolveValue($itemVariable, $compilationContext); $codePrinter->output('zephir_array_fast_append(' . $symbol . ', ' . $item . ');'); if ($itemVariable->isTemporal()) { $itemVariable->setIdle(true); } } } return new CompiledExpression('array', $symbolVariable->getRealName(), $expression); }
/** * Generate a random prime number. * * If there's not a prime within the given range, false will be returned. * If more than $timeout seconds have elapsed, give up and return false. * * @param Math_BigInteger $arg1 * @param Math_BigInteger $arg2 * @param int $timeout * @return Math_BigInteger|false * @access public * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. */ function randomPrime($arg1, $arg2 = false, $timeout = false) { if ($arg1 === false) { return false; } if ($arg2 === false) { $max = $arg1; $min = $this; } else { $min = $arg1; $max = $arg2; } $compare = $max->compare($min); if (!$compare) { return $min->isPrime() ? $min : false; } elseif ($compare < 0) { // if $min is bigger then $max, swap $min and $max $temp = $max; $max = $min; $min = $temp; } static $one, $two; if (!isset($one)) { $one = new Math_BigInteger(1); $two = new Math_BigInteger(2); } $start = time(); $x = $this->random($min, $max); // gmp_nextprime() requires PHP 5 >= 5.2.0 per <http://php.net/gmp-nextprime>. if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && extension_loaded('gmp') && version_compare(PHP_VERSION, '5.2.0', '>=')) { $p = new Math_BigInteger(); $p->value = gmp_nextprime($x->value); if ($p->compare($max) <= 0) { return $p; } if (!$min->equals($x)) { $x = $x->subtract($one); } return $x->randomPrime($min, $x); } if ($x->equals($two)) { return $x; } $x->_make_odd(); if ($x->compare($max) > 0) { // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range if ($min->equals($max)) { return false; } $x = $min->copy(); $x->_make_odd(); } $initial_x = $x->copy(); while (true) { if ($timeout !== false && time() - $start > $timeout) { return false; } if ($x->isPrime()) { return $x; } $x = $x->add($two); if ($x->compare($max) > 0) { $x = $min->copy(); if ($x->equals($two)) { return $x; } $x->_make_odd(); } if ($x->equals($initial_x)) { return false; } } }
/** * {@inheritDoc} * @see \Mdanter\Ecc\MathAdapterInterface::nextPrime() */ public function nextPrime($starting_value) { return gmp_strval(gmp_nextprime(gmp_init($starting_value, 10))); }