random_int
random_int(int $min, int $max): int
Generates a cryptographically secure random integer (both bounds inclusive).
C C23
#include <stdio.h>
// no CSPRNG in the C standard library; read random bytes from /dev/urandom (Linux/macOS universal)
static int roll_1_to_6(void) {
FILE *f = fopen("/dev/urandom", "rb");
unsigned char b;
if (f == NULL) return 1;
if (fread(&b, 1, 1, f) != 1) b = 0;
fclose(f);
return b % 6 + 1; // demo only; modulo bias — use rejection sampling in production
}
int main(void) {
int out_of_range = 0;
int seen[7] = {0};
for (int i = 0; i < 100; i++) {
int v = roll_1_to_6();
if (v < 1 || v > 6) out_of_range++;
else seen[v] = 1;
}
int distinct = 0;
for (int v = 1; v <= 6; v++) distinct += seen[v];
printf("out_of_range=%d\n", out_of_range);
printf("distinct>1=%s\n", distinct > 1 ? "true" : "false");
return 0;
}
out_of_range=0 distinct>1=true
C++ C++26
#include <iostream>
#include <random>
// random_device is an implementation-defined non-deterministic source (a CSPRNG on mainstream platforms)
static int roll_1_to_6() {
static std::random_device device;
return static_cast<int>(device() % 6) + 1;
}
int main() {
int out_of_range = 0;
bool seen[7] = {};
for (int i = 0; i < 100; i++) {
int v = roll_1_to_6();
if (v < 1 || v > 6) out_of_range++;
else seen[v] = true;
}
int distinct = 0;
for (int v = 1; v <= 6; v++) distinct += seen[v];
std::cout << "out_of_range=" << out_of_range << "\n";
std::cout << "distinct>1=" << (distinct > 1 ? "true" : "false") << "\n";
return 0;
}
out_of_range=0 distinct>1=true
C# v11.0.100
using System.Security.Cryptography;
var values = new int[100];
for (int i = 0; i < 100; i++) values[i] = RandomNumberGenerator.GetInt32(1, 7); // exclusive upper bound: 7 mirrors PHP (1, 6)
int outOfRange = 0;
bool[] seen = new bool[7];
foreach (int v in values) {
if (v < 1 || v > 6) outOfRange++;
else seen[v] = true;
}
int distinct = 0;
for (int v = 1; v <= 6; v++) {
if (seen[v]) distinct++;
}
Console.WriteLine($"out_of_range={outOfRange}");
Console.WriteLine($"distinct>1={(distinct > 1 ? "true" : "false")}");
out_of_range=0 distinct>1=true
Go v1.27.4
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
func main() {
outOfRange := 0
seen := map[int]bool{}
for i := 0; i < 100; i++ {
n, err := rand.Int(rand.Reader, big.NewInt(6)) // [0, 6), rejection-sampled with no modulo bias
if err != nil {
panic(err)
}
v := int(n.Int64()) + 1
if v < 1 || v > 6 {
outOfRange++
} else {
seen[v] = true
}
}
fmt.Printf("out_of_range=%d\n", outOfRange)
fmt.Printf("distinct>1=%v\n", len(seen) > 1)
}
out_of_range=0 distinct>1=true
Java v27.0.1
import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
SecureRandom random = new SecureRandom();
int outOfRange = 0;
Set<Integer> distinct = new HashSet<>();
for (int i = 0; i < 100; i++) {
int v = random.nextInt(6) + 1; // nextInt(6) is [0, 6) with no modulo bias
if (v < 1 || v > 6) outOfRange++;
else distinct.add(v);
}
System.out.println("out_of_range=" + outOfRange);
System.out.println("distinct>1=" + (distinct.size() > 1));
}
}
out_of_range=0 distinct>1=true
JavaScript v26.13.1
// Math.random is not crypto-safe; node:crypto.randomInt matches random_int
const { randomInt } = require("node:crypto");
const values = Array.from({ length: 100 }, () => randomInt(1, 7)); // exclusive upper bound
const outOfRange = values.filter((v) => v < 1 || v > 6).length;
const distinct = new Set(values).size;
console.log(`out_of_range=${outOfRange}`);
console.log(`distinct>1=${distinct > 1}`);
out_of_range=0 distinct>1=true
PHP v8.6.0
// random_int cannot be seeded and differs every run —
// the example asserts statistics instead: 100 samples inside [1,6] (always true) and diverse values (always true)
$values = [];
for ($i = 0; $i < 100; $i++) {
$values[] = random_int(1, 6);
}
$outOfRange = count(array_filter($values, function ($v) { return $v < 1 || $v > 6; }));
echo "out_of_range=$outOfRange\n";
echo "distinct>1=" . json_encode(count(array_unique($values)) > 1);
out_of_range=0 distinct>1=true
Python v3.15.2
# the random module (Mersenne Twister) is not crypto-safe; secrets is
import secrets
values = [secrets.randbelow(6) + 1 for _ in range(100)] # randbelow is rejection-sampled internally
out_of_range = sum(1 for v in values if v < 1 or v > 6)
distinct = len(set(values))
print(f"out_of_range={out_of_range}")
print(f"distinct>1={distinct > 1}")
out_of_range=0 distinct>1=True
Rust v1.99.1
use rand::rngs::OsRng;
use rand::Rng;
fn main() {
let mut out_of_range = 0;
let mut seen = [false; 7];
for _ in 0..100 {
let v = OsRng.gen_range(1..=6); // OsRng talks straight to the OS entropy source; gen_range has no modulo bias
if v < 1 || v > 6 {
out_of_range += 1;
} else {
seen[v as usize] = true;
}
}
let distinct = seen.iter().filter(|&&b| b).count();
println!("out_of_range={}", out_of_range);
println!("distinct>1={}", distinct > 1);
}
out_of_range=0 distinct>1=true
TypeScript v26.13.1
// Math.random is not crypto-safe; node:crypto.randomInt matches random_int
import { randomInt } from "node:crypto";
const values = Array.from({ length: 100 }, () => randomInt(1, 7)); // exclusive upper bound
const outOfRange = values.filter((v) => v < 1 || v > 6).length;
const distinct = new Set(values).size;
console.log(`out_of_range=${outOfRange}`);
console.log(`distinct>1=${distinct > 1}`);
out_of_range=0 distinct>1=true
Language differences
C: rand() is not cryptographically secure (predictable); the example reads /dev/urandom (the comment flags modulo bias — 256 % 6 ≠ 0 favors small values; production should use rejection sampling or platform APIs: Linux getrandom(2), macOS arc4random_uniform).
C++: random_device is an implementation-defined non-deterministic source (a CSPRNG on mainstream platforms, as in the example); engines like mt19937 are deterministic seeded PRNGs, not for cryptography.
C#: the Random class is not cryptographically secure (time-based seeds are predictable); RandomNumberGenerator.GetInt32(min, max+1) is the correct counterpart (the example comment spells out the exclusive upper bound).
Go: math/rand is not cryptographically secure; crypto/rand.Int(Reader, n) returns a big integer in [0, n) (example), rejection-sampled with no modulo bias; errors must be handled (err on entropy failure).
Java: java.util.Random is not cryptographically secure (48-bit seed, brute-forceable); SecureRandom.nextInt(6)+1 (example) has no modulo bias; the default provider is platform-dependent (NativePRNG on Linux).
JavaScript: Math.random is not cryptographically secure and cannot be seeded; Node's crypto.randomInt(1, 7) (example, exclusive upper bound) and the browser's crypto.getRandomValues are the secure choices.
PHP: random_int (7.0+) aggregates OS entropy and throws on failure instead of silently degrading; both bounds are inclusive (opposite of the C#/JS exclusive-upper APIs — aligned across the example). Determinism note: true randomness differs per run, so printing the random values would make the verification comparison fail every time — the example asserts statistics instead: range validity is guaranteed by the API contract; the probability of 100 identical rolls is 6/6^100 ≈ 3.8×10⁻⁷⁷, so the distinctness assertion holds for practical purposes.
Python: the random module is Mersenne Twister (predictable, seedable); secrets.randbelow(6)+1 (example) is the documented cryptographically secure form, rejection-sampled internally.
Rust: rand's OsRng (example) talks straight to the OS entropy source (getrandom(2)/arc4random); StdRng/SmallRng are seedable PRNGs, not for cryptography; gen_range is rejection-sampled.
TypeScript: same as JavaScript; in browsers crypto.getRandomValues(new Uint32Array(1))[0] % 6 + 1 carries modulo bias — prefer randomInt-equivalent helpers or rejection sampling.