Java program that prints out numbers that are divisible by other numbers

守給你的承諾、 提交于 2019-12-02 08:00:31

Well, you don't need a loop at all.

  1. You know that the number of numbers between x and y that are divisible by 2 is (y-x)/2 (plus minus one).

  2. Similarly the number of numbers between x and y that are divisible by 3 is (y-x)/3 (plus minus one).

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!