RaineAndrews
RaineAndrews

Reputation: 43

tests are right, but answer is still wrong

After a botched attempt at solving Euler problem 1 in C# using arrays, I was pointed toward using a single variable being added to only when the conditions of a for() loop are satisfied. The code is just plain better, but I can't see what I've done wrong.

The goal is to take the first 1000 numbers, find factors of 3 OR 5, and finally sum the factors up. I'm doing the first 10, which I know to be 23 before trying the full 1000. The console reads perfect up until the for() loop is finished, when I ask the code for the final answer at the end however, it gives me 33! How can the code add anything to the sum variable after the loop!!! Its taunting me...

using System;

public class Problem1
{
    public static void Main()
    {
        int sum = 0;

        //assign range to evaluate factors and summation
        int maxNumber = 10;

        //test if i is a factor of 5 or 3
        for(int i = 1; i <= maxNumber; i++)
        {
            if (i % 3 == 0 || i % 5 == 0)
            {
                //WriteLine here to debug, the real magic here is adding i to sum when test is true
                Console.WriteLine(sum);
                sum += i;
            }
        }

        //and the final answer is?
        Console.WriteLine(sum);

        //uncomment below line if running in vbs
        Console.ReadLine();
    }
}

Upvotes: 1

Views: 65

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186748

when

 maxNumber == 10

the selecred numbers are 3, 5, 6, 9, 10 the sum is 33 (not 23). General solution could be something like that (Linq):

int sum = Enumerable
  .Range(1, maxNumber)
  .Where(item => (item % 3 == 0) || (item % 5 == 0))
  .Sum();

when maxNumber == 1000 the answer is 234168. If you want to exclude maxNumber, just subtract 1:

int sum = Enumerable
  .Range(1, maxNumber - 1) // <- subtract 1
  .Where(item => (item % 3 == 0) || (item % 5 == 0))
  .Sum();

so the answer for 10 is 23 and for 1000 it's 233168

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39966

Because the maxNumber is also calculated.

Change this:

for(int i = 1; i <= maxNumber; i++) // i=3,5,6,9,10 => sum = 33

To this:

for (int i = 1; i < maxNumber; i++) // i=3,5,6,9  => sum = 23

Upvotes: 1

Bigsby
Bigsby

Reputation: 952

Let's "run" your code:

  • 1 ? Continue
  • 2 ? Continue
  • 3 ? Add
  • 4 ? Continue
  • 5 ? Add
  • 6 ? Add
  • 7 ? Continue
  • 8 ? Continue
  • 9 ? Add
  • 10 ? Add

Summed, 10, 9, 6, 5, and 3 is 33.

Upvotes: 3

Related Questions