Random Even or Odd numbers in a given range Or Set

Hi I am new to programming and need help with coming up with a "single" statement that will print a number at random from the set of :

a) 2, 4, 6, 8, 10

b) 3, 5, 7, 9, 11

I am using a + rand ()% b formula, where a is shifting value and be is the scaling factor. I can't figure out how to modify this formula to produce only Odd or Even numbers at random. Please help.

thanks a million
rand() always returns an integer.
So 2 * rand() is always an even integer.
And 2 * rand() + 1 is always an odd integer.
Somelauw,

Thank you. I appreciate your answer. Now, I understand why being good in math is important to programmer.

Below is the solution to original problems, but now I ran into third one.

a = 2 + (2 * rand ()) %10; //random numbers from set of 2, 4, 6, 8, 10

b = 3 + (2 * rand ()) %10; //random numbers from set of 3, 5, 7, 9, 11


I need to write "single" statement for random numbers from set of 6, 10, 14, 18, 22.

c = 6 + (2 * rand ()) %18;

//I used 18 as scaling factor instead of 16 because using 16 doesn't produce 22.

Above statement produces all even numbers between 6 and 22. Now, I need to figure how to filter out 8, 12, 16, 20, but I can't seem to figure it out. I have thought of trying various mathematical operators, but unsuccessful so far. The closest I got was using:

c = ((((2 * rand ()) %18) * 2) -10);

but it produces negative numbers and number below 6. I just can't figure out what I am missing. I have a feeling it is going to be something simple, but I am just not seeing it. Please help and let me know if there is general formula to figure out these different random number creations.


thanks a million

set of 6, 10, 14, 18, 22.
...
c = 6 + (2 * rand ()) %18;

Well you make jumps of 4 instead of 2.
Last edited on
Somelauw,

thanks again. It works. However, I had to use scaling factor of 20 instead of 18. I guess the concept is to (for set of even numbers) to add "step increase" (in this case 4) to highest number in set and then subtract the lowest number in set to get your scaling factor. And, you multiply rand() by the step increase as well.

For odd numbers, I noticed highest number in the set can be used as scaling factor, so no need to add or subtract. But, you still need to multiply rand() by step increase.

thanks.
Here's how I'd do all of them:

2,4,6,8,10:
1
2
3
4
5
6
// rand() % 5 yields 0, 1, 2, 3, or 4.
// adding 1 yields 1, 2, 3, 4, or 5.
// multiplying by 2 yields 2, 4, 6, 8, 10
int even_random_number() {
    return 2 * ( rand() % 5 + 1 );
}


3,5,7,9,11:
1
2
3
int odd_random_number() {
    return 1 + even_random_number();
}


6, 10, 14, 18, 22:
1
2
3
int new_random_number() {
   return 2 * odd_random_number();
}


Now you can easily turn these functions into 1-liners.
Thanks jsmith. This is smart way to do all of them. It was educational.
Topic archived. No new replies allowed.