! How to quickly generate a random number

Source: Internet
Author: User
Help! How to quickly generate a random number! The requirement is as follows: a member purchases an order number, which must be a number and data within a certain range, such as & nbsp; 1 & nbsp; to & nbsp; 0.1 million. The method I use now is & nbsp; use & nbsp; rand () to generate a random number. after obtaining this random number, I will go to the database to check it again, if this number already exists, repeat it. The code is as follows: help! How to quickly generate a random number!
The requirement is as follows:
A member purchases an order number, which must be a number within a certain range, such as 1 to 0.1 million.

I am using rand () to generate a random number. after obtaining the random number, I will check it in the database. if this number already exists, I will query it again in a loop.
The code is as follows:

set_time_limit(0);
$test = M('test');
$_run = true;
$_order_id = rand(0, 100000);
while ($_run) {
$orderInfo = $test->where("val = ".$_order_id)->find();
if(empty($orderInfo)){
$_run = false;
return $_order_id;
}else{
$_order_id = rand(0, 100000);
}
}


In this way, when the order number is still very small, it is easy to get the order number, if the order number has reached 99990
It takes a long time to generate other order numbers at this time, which may take several minutes or even an hour.

This method does not work.

Please help me find a solution or provide other ideas. thank you!
------ Solution ----------------------
You can write a pseudo-random number generator by yourself.
First observe
$m = 100000;
$c = 101;
$b = 81;
$n = 0;
for($i=0; $i<100000; $i++) {
$n = ($n * $c + $b) % $m;
$r[] = $n;
}
print_r(array_count_values(array_count_values($r)));
Array
(
[1] => 100000
)
We can see that $ r contains 0-99999 random numbers, and each number appears only once.

If $ n is the number of the last database entry, ($ n * $ c + $ B) % $ m is definitely not in the database.

Hope you can understand

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.