0

I have this assignment in school; we are to write a simple program/method/algorithm in java that has us take two numerical inputs and output count of all the numbers in the range between two inputs which are dividable by 2 or 3 or 5.

The assignment is fairly simple, since you can just iterate through all the numbers in range and increment the counter whenever all the criteria is met.

But we also get 10 test inputs and a timer that evaluates the efficiency of our algorithm. First eight fell through, since the eight values were < 10^6. But the last two test input vales were < 10^18 and my algorithm failed.

So I started thinking in the direction of prime number counting function and sieve Eratosthenes, but my head started to hurt. Any ideas on a faster but still simple enough algorithm?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
kamenjan
  • 119
  • 2
  • 11

1 Answers1

4

I came up with something like that

public static void main(String[] args) {
    long a = 123456789012345678L, b = 876543210987654321L;
    long score = getCount(b) - getCount(a - 1);
    System.out.println("Divisible by 2 or 3 or 5: " + score);
}

public static long getCount(long end) {
    return (end / 2) + (end / 3) + (end / 5) - ((end / 6)  + (end / 10) + (end / 15)) + (end / 30);
}

The solution:

  • It counts how many numbers are divisible by 2 or 3 or 5 separately and sums that.
  • Now we need to discard numbers that where counted twice: for 2 and 3 it will be every 6th number, for 2 and 5 every 10th number, for 3 and 5 every 15th number
  • At the end we need to include numbers that are divisible by 2 and 3 and 5 that where discarded in step 2 so we add every 30th number.
StackFlowed
  • 6,664
  • 1
  • 29
  • 45
  • 2
    Why not just compute `end / 30`, since any number divisible by 2, 3, and 5 must be divisible by 30 = 2 * 3 * 5? – John Bollinger Nov 07 '14 at 17:50
  • In any case, one point of the exercise appears to be to show that determining how many there are of some thing is not the same thing as finding all of those things, as this answer demonstrates. – John Bollinger Nov 07 '14 at 17:53
  • @JohnBollinger It depends on how you read the problem, which is not clearly stated. The answer finds the count of numbers that are divisible by 2 *or* by 3 *or* by 5 (or by more than one of these). But if you read the problem as "look for the numbers that are divisible by 2, *and* the numbers that are divisible by 3, *and* the numbers that are divisible by 5, then count them all", this is mathematically imprecise but OK in informal English. – ajb Nov 07 '14 at 17:54
  • and, ... this is known as [inclusion-exclusion principle](http://en.wikipedia.org/wiki/Inclusion–exclusion_principle), – Will Ness Nov 08 '14 at 13:03