How do I generate random Integers within a Specific Range?
To generate random integers within a specific range in most languages, you can use the Random class or built-in methods.
The formula typically involves generating a random number and scaling it to the desired range.
For example, to generate a number between min and max, you can use random.nextInt(max – min + 1) + min.
You can generate random integers within a specific range using the following methods:
Java
import java.util.Random
public class Main, public static void main (StringL args) {int min = 1;int max = 100;
Random rand = new Random
Method: Using Random.nextInt()
int randomInt = rand.nextInt((max – min) + 1) + min
System.out.println(randomInt)
Python
import random
min_value = 1
max_value = 100
Method 1: Using random.randint()
random_int = random.randint(min_value, max_value)
print(random_int)
Method 2: Using random.randrange()
random_int = random.randrange(min_value, max_value + 1)
print(random_int)