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.
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 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.