views:

551

answers:

4

I know that this can be easily done by using

if(i%5 == 0 OR i%3 ==0) sum+=i;

But what is wrong in the following C#code:

    int sum = 0;
 for(int i = 0, j = 0; i < 1000; i+=3, j+=5)
 {
  Console.WriteLine("i = " + i);
  Console.WriteLine("j = " + j);

  sum += i;

  Console.WriteLine("Sum after adding i  = " + sum);

  if(j < 995 && j % 3 != 0)
  {
   sum += j;
  }

  Console.WriteLine("Sum after adding j  = " + sum);

 }
A: 

This is just a nit-pick, maybe, but still: "All" and "lower than 1,000" is not the same set of natural numbers, you might want to change something.

unwind
" it risks adding the same number more than once" . How?
Sandbox
It doesn't, unwind is wrong about that. Your checks are sufficient to prevent adding the same number multiple times (although your loop design is unorthodox and a little confusing at first read).
Tyler McHenry
+1  A: 

The obvious bug is that 995 is a multiple of 5 that won't get added, while 996 and 999 are multiples of 3 that will be added: the 1000 in the loop condition and the 995 in the if condition should be the same number.

Dave Hinton
+4  A: 

The statement j < 995 should probably be j <= 995, otherwise you are not going to add 995 to your sum.

Tyler McHenry
yes. That is the issue. I should have figured it out myself. Thanks.
Sandbox
j < 1000 would be a little more pure
xan
+1  A: 

Also, if you want to sum all such natural numbers less than 1000, why excluding 995? You could put

j <= 995 && j%3!=0
Aviator