Skip to content

Commit

Permalink
GH-13661: implements gmp_prevprime.
Browse files Browse the repository at this point in the history
Sets the GMP instance to the greatest prime < than the argument
provided (or left the instance unmodified).
  • Loading branch information
devnexen committed Oct 26, 2024
1 parent f4e2031 commit 9a2af3c
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 1 deletion.
1 change: 1 addition & 0 deletions ext/gmp/config.m4
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,5 @@ if test "$PHP_GMP" != "no"; then
PHP_SUBST([GMP_SHARED_LIBADD])
AC_DEFINE([HAVE_GMP], [1],
[Define to 1 if the PHP extension 'gmp' is available.])
AC_CHECK_FUNCS([__gmpz_prevprime])
fi
25 changes: 25 additions & 0 deletions ext/gmp/gmp.c
Original file line number Diff line number Diff line change
Expand Up @@ -2080,6 +2080,31 @@ ZEND_FUNCTION(gmp_scan1)
}
/* }}} */

#ifdef HAVE___GMPZ_PREVPRIME
ZEND_FUNCTION(gmp_prevprime)
{
zval *a_arg;
mpz_ptr gmpnum_a, gmpnum_result;
gmp_temp_t temp_a;

if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &a_arg) == FAILURE){
RETURN_THROWS();
}

FETCH_GMP_ZVAL(gmpnum_a, a_arg, temp_a, 1);
INIT_GMP_RETVAL(gmpnum_result);

/*
* If it leads to a prime number the resulting
* GMP instance will reflect the change anyway ;
* on certainty (returning 2) or probability (1).
*/
(void)mpz_prevprime(gmpnum_result, gmpnum_a);

FREE_GMP_TEMP(temp_a);
}
#endif

ZEND_METHOD(GMP, __construct)
{
zend_string *arg_str = NULL;
Expand Down
4 changes: 4 additions & 0 deletions ext/gmp/gmp.stub.php
Original file line number Diff line number Diff line change
Expand Up @@ -184,3 +184,7 @@ function gmp_hamdist(GMP|int|string $num1, GMP|int|string $num2): int {}
function gmp_nextprime(GMP|int|string $num): GMP {}

function gmp_binomial(GMP|int|string $n, int $k): GMP {}

#ifdef HAVE___GMPZ_PREVPRIME
function gmp_prevprime(GMP|int|string $num): GMP {}
#endif
14 changes: 13 additions & 1 deletion ext/gmp/gmp_arginfo.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions ext/gmp/tests/gh13661.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
--TEST--
gmp_prevprime()
--EXTENSIONS--
gmp
--SKIPIF--
<?php if (!function_exists("gmp_prevprime")) die("skip no gmp_prevprime"); ?>
--FILE--
<?php

var_dump(gmp_prevprime(-1));
var_dump(gmp_prevprime(1));
var_dump(gmp_prevprime(3));
var_dump(gmp_prevprime(gmp_init("3")));
var_dump(gmp_prevprime(gmp_init(PHP_INT_MAX)));

?>
--EXPECTF--
object(GMP)#1 (1) {
["num"]=>
string(1) "0"
}
object(GMP)#1 (1) {
["num"]=>
string(1) "0"
}
object(GMP)#1 (1) {
["num"]=>
string(1) "2"
}
object(GMP)#1 (1) {
["num"]=>
string(1) "2"
}
object(GMP)#1 (1) {
["num"]=>
string(19) "%d"
}

0 comments on commit 9a2af3c

Please sign in to comment.