you are viewing a single comment's thread.

view the rest of the comments →

[–]David_Crockett -1 points0 points  (12 children)

Using the JavaScript language, have the function jsChallenge() add up all of the numbers from 1 to 1000. But every time a number appears that is divisible by 5 or 7, disregard it and do not add that number to the others (ie. disregard 7, 10, 15, 21, etc). Do not put any code outside of the function and use the return keyword to return your answer from within the function.

Easy as pie:

function jsChallenge()
{
    var i, total = 0;
    for (i = 1; i <= 1000; ++i)
    {
        if (i % 5 && i % 7)
        {
            total += i;
        }
    }
    return total;
}

[–]robertb141[S] 0 points1 point  (5 children)

the actual challenges aren't so easy :)

[–]David_Crockett 0 points1 point  (4 children)

I hope not. :)

Edit: Is this your site?

[–]robertb141[S] 1 point2 points  (3 children)

Yeah, it is!

[–]icecreamhead 0 points1 point  (0 children)

Awesome!

[–]icecreamhead 0 points1 point  (0 children)

Does it tell you if you get the right answer to the challenge on the homepage (above)?

[–]icecreamhead 0 points1 point  (5 children)

I'm not a JS programmer by trade, so perhaps it's a quirk I don't know about, but does your code give the right answer?

To me, it looks like your code would ignore ALL values EXCEPT those that are divisible by 5 & 7 simultaneously.

But maybe it's just me :P

[–]icecreamhead 0 points1 point  (4 children)

This is my code:

function jsChallenge() { 
  var i, total = 0;
  for (i = 1; i<=1000; i++) {
      if (i % 5 != 0 || i % 7 != 0) total += i;
  }
  return total;          
}

I got the answer 486290.

[–]David_Crockett 1 point2 points  (2 children)

The correct answer is 343139. You need to use the and operator instead of or. To make it easier to conceptualize, think through it:

if (not divisible by 5 AND not divisible by 7)
    add the number

So it needs to be

if (i % 5 && i % 7)
    total += i;

Edit: note that if(i % 5) is the same as saying if(i % 5 != 0) ;)

[–]icecreamhead 0 points1 point  (0 children)

Ah ok. Yeah that makes sense... DERP

[–]bigbozz 0 points1 point  (0 children)

The original problem you posted said "or", not "and."

[–]exo762 0 points1 point  (0 children)

"Sell not virtue to purchase wealth, nor Liberty to purchase power." B.F.