0

I'm using bcmod and gmp_mod functions in php for handling large numbers.

This works fine:

// large number must be string
$n = "10000000000000000000001";
$y = 1025;
$c = 1025;
// Both works the same (also tested in python)
$y = gmp_mod( (bcpowmod($y, 2, $n) + $c) , $n);
$y = bcmod  ( (bcpowmod($y, 2, $n) + $c) , $n);

But the input $n is not static. So I must use type casting like:

$n = (string)10000000000000000000001;

This doesn't work anymore.

for gmp gives this error:

gmp_mod(): Unable to convert variable to GMP - string is not an integer

And about bc, gives me this error:

bcmod(): Division by zero

The problem is, (string) doesn't convert it to string fine. Any idea?

Edit: I found a solution here, but still the input is string:

$bigint = gmp_init("9999999999999999999");
$bigint_string = gmp_strval($bigint);
var_dump($bigint_string);

1 Answer 1

1

If You are taking an input for $n it would give you as a string not as int and if you have type casted as int at any point ... taking care the max size of int, the above given no is converted to 1.0E+22 now what happens when you try to type cast (string)1.0E+22 it becomes "1.0E+22" which is obviously just a string and can not be converted to gmp number.

So You need to convert scientific notation to string which will auto include , hence you also need to replace those commas

$n = 10000000000000000000001;
$n = str_replace(",", "", number_format($n));
Sign up to request clarification or add additional context in comments.

4 Comments

I know the reason, just looking for a solution.
never define the type of $n and it will always be a string ...if taking inputs from ... you ca't typecast
Thank you. But it doesn't return the exact value. In your case it returns 10000000000000000000000
yah doing this we loose precision .. So its a strict warning on php.net to use string for big numbers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.