How can I generate a number not exceeding a specific range?
Example:
I want to generate a number that has 70 digits but doesn't exceed "90000000000000000000000000000000000000000000000000000000000000000000000"
How to do that?
I tried using gmp_init
$range1 = gmp_init("100000000000000000000000000000000000000000000000000000000000000000000000000");
$range2 = gmp_init("900000000000000000000000000000000000000000000000000000000000000000000000000");
$generatedValue = rand($range1,$range2);
echo $generatedValue;
However, it outputs the following error:
PHP Warning: rand() expects parameter 1 to be int, object given
I tried rand(), mt_rand(), random_byte()...
Another Try:
<?php
$rand1 = gmp_random_range(100000000000000000000000000000000000000000000000000000000000000000000000000,900000000000000000000000000000000000000000000000000000000000000000000000000>
echo gmp_strval($rand1) . "\n";
Error: PHP Warning: gmp_random_range(): Unable to convert variable to GMP - wrong type in /home/ubuntu/test/test5.php on line
Let's clear up a few points of confusion:
Bearing all that in mind, we can look at the list of GMP functions in the manual, and find this:
gmp_random_range(GMP|int|string $min, GMP|int|string $max): GMP
Just what we need! Note that it can take arguments of three different types:
So the simplest way to write your example is:
$rand1 = gmp_random_range('100000000000000000000000000000000000000000000000000000000000000000000000000','900000000000000000000000000000000000000000000000000000000000000000000000000');
This will return a GMP object, so you'll need to look for other GMP functions to decide what to do with it next.
Numbers in php - and most programming languages - has max and min values you can not go beyond.
Maximum integer in php defined in PHP_INT_MAX , Maximum float defined in PHP_FLOAT_MAX.
But if you want a random string larger than this maximum number bounds. You can string concatenation many random numbers to get this random string:
$largeRandomString = mt_rand(10000000, 99999999).mt_rand(10000000, 99999999).mt_rand(10000000, 99999999).mt_rand(10000000, 99999999);
This solution generates a string with a fixed length of 70 characters and evenly spaced digits from 0 to 9. Only basic PHP functions are required. The algorithm must be modified for 32-bit systems.
$min = "1000000000000000000000000000000000000000000000000000000000000000000000";
$max = '9000000000000000000000000000000000000000000000000000000000000000000000';
do{
for($str = "", $i=0; $i < 7; $i++){
$str .= sprintf("%010d",mt_rand(0,9999999999));
}
}while($str < $min OR $str > $max);
var_dump($str);
//string(70) "8225821562698285549247617814952633507395510882337701683734245940552330"
The range filter is based on a simple string comparison. For this, $min and $max must contain exactly 70 characters.