Skip to main content
Back to problems
#470
Medium Algorithms

Implement rand10 using rand7

Math Rejection Sampling Randomized Probability and Statistics
46.2% acceptance
Jan 13, 2026
1171
388
Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API. Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::sync::atomic::{AtomicU64, Ordering};

static COUNTER: AtomicU64 = AtomicU64::new(0);

fn rand7() -> i32 {
  use std::time::{SystemTime, UNIX_EPOCH};
  let seed = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .unwrap()
    .as_nanos();
  let count = COUNTER.fetch_add(1, Ordering::SeqCst);
  ((seed.wrapping_add(count as u128) % 7) as i32) + 1
}

impl Solution {
  pub fn rand10() -> i32 {
    loop {
      let row = rand7();
      let col = rand7();
      let idx = col + (row - 1) * 7;

      if idx <= 40 {
        return 1 + (idx - 1) % 10;
      }
    }
  }
}