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

前端 未结 2 1329
余生分开走
余生分开走 2021-01-28 01:25

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

2条回答
  •  终归单人心
    2021-01-28 01:43

    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.

提交回复
热议问题