Rory Perro
Rory Perro

Reputation: 451

Add all the values between 100 and 4000000 inclusively that are divisable by 3 or 5 but not both 3 and 5

Add all the values between 100 and 4000000 inclusively that are divisable by 3 or 5 but not both 3 and 5

Can't figure out how to implement second part of that stipulation. Here's what I have so far:

var sum = 0;
for (var i = 100; i < 4000001; i++) {
    if (i % 3 || i % 5 === 0) {
        sum = sum + i;
    } 
}

Upvotes: 1

Views: 245

Answers (4)

Qbyte
Qbyte

Reputation: 13243

You can use != instead of || since this is exactly what you want. Only divisible by 3 or 5 but not by both.

var sum = 0;
for (var i = 100; i < 4000001; i++) {
    if ((i % 3 == 0) != (i % 5 == 0)) {
        sum = sum + i;
    } 
}

Upvotes: 1

Niklas B.
Niklas B.

Reputation: 95308

You can compute the sum without any loop, using the formula for the sum of an arithmetic progression: We have

    3 + 5 + 6 + 9 + 10 + 12 + 18 + 20 + ...
=   3 + 6 + 9 + 12 + 15 + 18 + ...
  + 5 + 10 + 15 + 20 + ...
  - 2*(15 + 30 + 45 + ...)

Note that we add all the multiples of 3 and 5 but then subtract the multiples of 15 twice, because they were counted twice as multiples of both 3 and 5.

Let g(n) be the sum of integers from 1 to n. We have g(n) = n*(n+1)/2.

Let f(n) be the sum of integers between 1 and n that are divisible by 3 or 5, but not both. Then we have

f(n) = 3*g(floor(n / 3)) + 5*g(floor(n/5)) - 30*g(floor(n/15))

And the sum of integers between m and n that are divisible by 3 or 5, but not both is then just f(n) - f(m - 1). This can be computed in O(1).

Upvotes: 6

var sum = 0;
for (var i = 100; i < 4000001; i++) {
    if (i % 3 === 0 ^ i % 5 === 0) {
       sum = sum + i;
   } 
}

use the exclusive OR , XOR ^ returns true only when one of the conditions not both is true.

Upvotes: 0

Am_I_Helpful
Am_I_Helpful

Reputation: 19158

You simply need to escape only those part which involves division by 15, and other higher numbers(multiple of 15) will be avoided further automatically.

Note that checking divisibility by 15 should be at the top, which on being true will continue further iteration without executing the below codes of divisibility by 3 and 5. If false, then a number can only be divisible by 3 or 5 or none, but not both.

for (var i = 100; i < 4000001; i++) {
   if(i % 15 == 0 )
    continue;
   if (i % 3  == 0) {
    sum = sum + i;
   } 
   if (i % 5  == 0) {
    sum = sum + i;
   } 
}

Also, note that you have used === operator which I don't think is a valid operator, probably you want ==. BTW, I am not sure whether any language supports ===, I think Javascript supports that. So, be careful at that step.

Upvotes: 2

Related Questions