# leetcode\_470

Given the API rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10. You can only call the API rand7 and you shouldn't call any other API. Please don't use the system's Math.random().

Notice that Each test case has one argument n, the number of times that your implemented function rand10 will be called while testing.

Follow up:

What is the 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] Example 3:

Input: n = 3 Output: \[3,8,10]

Constraints:

1 <= n <= 105

## Solutions

1. **math**
2. Strongly recommended referece: <https://leetcode-cn.com/problems/implement-rand10-using-rand7/solution/cong-zui-ji-chu-de-jiang-qi-ru-he-zuo-dao-jun-yun-/>
3. In short:
   * `randN()` can be implemented by sampling from `(randX() - 1) * Y + randY() s.t. XY == N`
   * `randN()` can be ... from `(randM() % N + 1 s.t. M == xN, x >= 1`

     \`\`\`cpp

     // The rand7() API is already defined for you.

     // int rand7();

     // @return a random integer in the range 1 to 7

class Solution { public: int rand10() { while (true) { int num = (rand7() - 1) \* 7 + rand7(); if (num <= 40) return (num % 10) + 1; } } }; \`\`\`
