__zac__'s blog

By __zac__, history, 4 years ago, In English

I'm trying to solve this problem on SPOJ using inclusion-exclusion principle but I can't get the correct answer. My code

    private static void solve(long n, long m, long a, long d) {
        long[] values = new long[5];

        for (int i = 0; i < 5; i++) {
            values[i] = a + i*d;
        }

        long left, right, sum = 0, diff = m-n+1;

        for (int i = 0; i < (1 << 5); i++) {
            int count = 0;
            long divisor = 1;
            for (int j = 0; j < 5; j++) {
                if ((i & (1 << j)) > 0) {
                    count++;
                    divisor = lcm(divisor, values[j]);
                }
            }
            left = (n-1)/divisor;
            right = m/divisor;
            if (count % 2 == 0) sum -= right-left;
            else sum += right - left;
        }
        System.out.println(diff-sum);
    }

    private static long lcm(long a, long b) {
        return (a*b)/gcd(a,b);
    }

    private static long gcd(long a, long b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a%b);
    }
  • Vote: I like it
  • -2
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Why 2 << 5, shouldn’t it be 1 << 5?

»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Maybe lcm function is overflowing, share the code.