I have a program that reads two real numbers and then it prints out all the numbers between these two, that are divisible by 2 or 3 or 5. The program works fine, but when a use
Not really an answer, but with my low reputation score I am not permitted to post a comment.
If a number is divisible by 2, or 3, or 5 does not change if you add or subtract 30 (= 2* 3* 5) from that number. So you can count the matching numbers from 1 to 30, then compute how many blocks of 30 numbers are in your range, and then count the matching numbers that are not covered by those blocks.
Well, you don't need a loop at all.
You know that the number of numbers between x and y that are divisible by 2 is (y-x)/2 (plus minus one).
Similarly the number of numbers between x and y that are divisible by 3 is (y-x)/3 (plus minus one).
And the number of numbers between x and y that are divisible by 5 is (y-x)/5 (plus minus one).
You just have to remove the numbers you counted more than once.
If you consider groups A, B & C, the groups of numbers divisible by 2, 3 and 5 (in the required range) respectively, your goal is to find :
|A union B union C| = |A| + |B| + |C| - |A intersection with B| - |A intersection with C| - |B intersection with C| + |A intersection with B intersection with C|
Therefore, you have to subtract the numbers divisible by 2*3, the numbers divisible by 2*5 and the numbers divisible by 3*5. Finally, you have to add the numbers divisible by 2*3*5.
Example :
between 1000 and 2000 there are about (2000-1000)/2 = 500 numbers divisible by 2 : 1000,1002,1004,...,2000. Actually, the count is off by 1, since it's 501 and not 500, but you can adjust for that by adding some logic that checks the edges of the range.
similarly, there are about (2000-1000)/3 = 333 numbers divisible by 3 : 1002, 1005, 1008, ..., 1998.
And about (2000-1000)/5 = 200 numbers divisible by 5 : 1000,1005,1010,...,2000. Here the count is again off by one.