> For the complete documentation index, see [llms.txt](https://txfs19260817.gitbook.io/leetcode-go-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://txfs19260817.gitbook.io/leetcode-go-notes/solutions/470.-implement-rand10-using-rand7.md).

# 470. Implement Rand10() Using Rand7()

## LeetCode [**470. Implement Rand10() Using Rand7()**](https://leetcode-cn.com/problems/implement-rand10-using-rand7/)\*\*\*\*

### Description

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()`.

**Follow up:**

* What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function?
* Could you minimize the number of calls to `rand7()`?

**Example 1:**

```
Input: n = 1
Output: [2]
```

**Example 2:**

```
Input: n = 2
Output: [2,8]
```

**Constraints:**

* `1 <= n <= 105`

### Tags

Math

### Solution

![](https://3979976701-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MWCWmbVhbhatBCAMIGH%2Fuploads%2Fgit-blob-3a0a66af646b6b6804ef3b8934fce83671bcde21%2Fimage%20\(6\).png?alt=media)

We randomly choose a position via `(row-1)*7 + (col-1)` in the table above, and repeat this procedure until we can obtain a number between 1 and 10 rather than '\*'.

### Complexity

* Time complexity: $$O(1) \rightarrow O(\infty)$$
* Space complexity: $$O(1)$$

### Code

```go
func rand10() int {
	t := 40
	for t >= 40 {
		t = (rand7()-1)*7 + (rand7() - 1)
	}
	return t%10 + 1
}
```

## Reference

1. [用 Rand7() 实现 Rand10()](https://leetcode-cn.com/problems/implement-rand10-using-rand7/solution/yong-rand7-shi-xian-rand10-by-leetcode/)
