GrumpyKitten
GrumpyKitten

Reputation: 35

Code does not work for large numbers

I'm just starting with coding here, so bear with me, please. I tried doing this simple task (at least it looked simple), which states: "Read two integers, then write out all of them that are dividable by either 2, 3, or 5. My code has no problems dealing with small numbers, however it gets complicated when I get into millions. The program just times out, or takes a ridiculous amount of time to calculate. Help appreciated!

import java.util.Scanner;

class Veckratniki {
    public static void main(String[] args) {
        long v = 0;
        Scanner sc = new Scanner(System.in);
        long a = sc.nextLong();
        long b = sc.nextLong();
        while (a <= b) {
            if ((a % 2 == 0) || (a % 3 == 0) || (a % 5 == 0)) {
                v++;
                a++;
            } else {
                a++;
            }
        }
        System.out.println(v);
    }
}

Upvotes: 0

Views: 85

Answers (1)

Henry
Henry

Reputation: 43728

If you just need to count these numbers you can speed up the program dramatically by using some mathematics, namely the inclusion exclusion principle.

I call N(x) the count of numbers in the range divisible by x.

The answer is then N(2) + N(3) + N(5) - N(6) - N(10) - N(15) + N(30).

I leave it as an exercise to determine N(x); hint: it will be close to range / x.

Upvotes: 1

Related Questions