Kotlin Program to Generate Random Number
val randomNumber = kotlin.random.Random.nextInt() for any integer or Random.nextInt(from, until) for a range.Examples
How to Think About It
Algorithm
Code
import kotlin.random.Random fun main() { val randomNumber = Random.nextInt(1, 101) // random number from 1 to 100 println("Random number between 1 and 100: $randomNumber") }
Dry Run
Let's trace generating a random number between 1 and 100 through the code
Call Random.nextInt(1, 101)
Generates a random integer starting at 1 up to but not including 101
Store the result in randomNumber
randomNumber = 57 (example value)
Print the randomNumber
Output: Random number between 1 and 100: 57
| Step | randomNumber |
|---|---|
| 1 | 57 |
Why This Works
Step 1: Using Random.nextInt()
The Random.nextInt() function generates a random integer. If you provide two arguments, it generates a number from the first argument (inclusive) to the second (exclusive).
Step 2: Specifying a range
By giving 1 and 101, you get numbers from 1 to 100 because the upper bound is exclusive.
Step 3: Printing the result
The println statement shows the random number so you can see the output.
Alternative Approaches
import java.util.Random fun main() { val random = Random() val randomNumber = random.nextInt(100) + 1 // 1 to 100 println("Random number between 1 and 100: $randomNumber") }
import java.util.concurrent.ThreadLocalRandom fun main() { val randomNumber = ThreadLocalRandom.current().nextInt(1, 101) println("Random number between 1 and 100: $randomNumber") }
Complexity: O(1) time, O(1) space
Time Complexity
Generating a random number is a constant time operation because it does not depend on input size.
Space Complexity
Only a single integer variable is used to store the random number, so space is constant.
Which Approach is Fastest?
Kotlin's built-in Random is optimized and simple; Java's Random and ThreadLocalRandom add overhead but are useful in specific contexts.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Kotlin Random.nextInt() | O(1) | O(1) | Simple and idiomatic Kotlin code |
| Java Random.nextInt() | O(1) | O(1) | Legacy Java compatibility |
| ThreadLocalRandom.nextInt() | O(1) | O(1) | Multi-threaded environments |
Random.nextInt(from, until) to get a random number within a specific range easily.Random.nextInt(from, until) is exclusive, causing off-by-one errors.