VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-integer-from-1-to-7-with-equal-probability/

⇱ Generate integer from 1 to 7 with equal probability - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate integer from 1 to 7 with equal probability

Last Updated : 19 Mar, 2026

Given a function foo() that returns integers from 1 to 5 with equal probability, write a function that returns integers from 1 to 7 with equal probability using foo() only. Minimize the number of calls to foo() method. Also, use of any other library function is not allowed and no floating point arithmetic allowed.

Examples:

Input: foo() - returns 1 to 5
Output: Generate numbers from 1 to 7 with equal probability.
Explanation: Generate values from 1 to 25, keep values less than 22, and map them to 1 to 7 using modulo.

Input: foo() - returns 1 to 5
Output: 4

[Approach] Using Rejection Sampling - O(1) Time and O(1) Space

The idea is to generate a value using 5 * foo() + foo() - 5, check if it is less than 22, and convert it to a number from 1 to 7 using modulo; otherwise, repeat the process until a valid value is obtained.


Output
1 
Comment
Article Tags: