VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-generate-a-random-three-digit-even-number/

⇱ Program to generate a random three digit even number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to generate a random three digit even number

Last Updated : 18 Jan, 2024

Write a program to generate a random three-digit even number.

Examples:

Example 1: 482
Example 2: 736

Approach: To solve the problem, follow the below idea:

We can generate a random three-digit number by generating a random integer first and then modulo it by 900. Now, after modulo with 900, the remainder can be in the range 0 to 899, so in order to have the remainder as a three-digit number only, we can further add 100 to make the range 100 to 999. If the generated number is equal to 999, then decrement it by 1. Else, if the generated number is an odd number other than 999, increment it by 1 to get the random three-digit even number.

Step-by-step algorithm:

  • Generate a random number and modulo it by 900.
  • Now, add 100 to the remainder.
  • If the generated number is 999, decrement it by 1 to get 998.
  • Otherwise, if the generated number is some other three-digit odd number, increment it by 1 to get the required three-digit number.

Below is the implementation of the algorithm:


Output
Generated number: 448

Time Complexity: O(1), The algorithm generates a random number in constant time.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: