While working with algorithms we often come across situations when we need to generate random integers. The most common way to generate random numbers is using Mersenne Twister.
The Mersenne Twister is a pseudorandom number generator which got its name derived from the fact that its period length is chosen to be a Mersenne prime. It was the first pseudorandom number generator to provide fast generation of high-quality pseudorandom integers. It was designed specifically to rectify most of the flaws found in older pseudorandom number generators.
So in PHP, there is an inbuilt function mt_rand() which is based on Mersenne Twister which helps in generating random numbers.
The mt_rand() function generates a random integer between the specified minimum and maximum values. It produces a better random value and is faster than the rand() function. You may also refer to the article on PHP | rand() Function which is another inbuilt function in PHP to generate random numbers.
int mt_rand($min, $max)
Parameters: This function accepts two parameter which are described below:
- $min : It is an optional parameter. It specifies the lowest number to be returned.The default value is 0.
- $max : It is an optional parameter. It specifies the highest number to be returned.
Return Value: It returns a random number between min (or 0) and max and the return type is integer.
Input : mt_rand() Output : 34567 Input : mt_rand(15, 50) Output : 49
Below programs illustrate the working of mt_rand() in PHP:
Important points to note :
- mt_rand() function generates a random integer using the Mersenne Twister algorithm.
- It produces a better random value and is faster than the rand() function.