Write code that generates a random odd integer (not divisible by 2) between 50 and 99 inclusive. Fill in the values of the sub-expressions labeled A, B, and C below.
Random rand = new Random(); int n = rand.nextInt(A) * B + C;
The answer is A = 25; B = 2; C =51
What I have tried:
I dont get the answer. rand.nextInt(25) meansa range of 0-24 right. Then, you multiply by 2 so the range becomes 0-48. Last you add 51 so the final range becomes 51 - 99, but the problem says the range is 50-99. Can someone explain to me how to get range of 50-99 with answers of A = 25; B = 2; C =51
解决方案
You are required to generate odd numbers only: so the value you add on - C - must be odd, and the original value - rand.nextInt(A) * B must be even, which means that B must be even.
So your tutor has selected B = 2, C = 51 which fulfils the "must be odd" requirement, and offsets the number so that it is 51 or greater under all circumstances. Since 51 is the first odd value greater than 50 it fits the low end of the range as well.
A controls the original range of values: 25 will indeed give you numbers from 0 to 24, so the complete expression will give values like this:
A = 0 : 0 * 2 + 51 == 0 + 51 == 51
A = 1 : 1 * 2 + 51 == 2 + 51 == 53
A = 2 : 2 * 2 + 51 == 4 + 51 == 55
...
A = 22: 22 * 2 + 51 == 44 + 51 == 95
A = 23: 23 * 2 + 51 == 46 + 51 == 97
A = 24: 24 * 2 + 51 == 48 + 51 == 99Which fits all your criteria.
Quote:51 - 99, but the problem says the range is 50-99.Indeed taht's the range. But, unfortunately 50 is even, hence 51 is the first valid entry of the requested range.