søndag den 30. juni 2013

Project euler problem #2: An interesting alternative "solution"

I have stepped across the site called project euler. An nifty site for using your skills as a programmer to solve different problems including doing an algorithm.

In my time being an Software engineering student in the 4. semester. I have learned that you should always try to seperate your problem into smaller subproblems, and find the solution to them.

I tried that, and here was the result:


//find the multiples of 3
        private static int MultipleOfThree()
        {
            int result = 0;
            for (int i = 0; i < 1000; i++)
            {
                if (i % 3 == 0)
                {
                    result = result + i;
                }
            }
            return result;
        }
        //find the multiples of 5
        private static int MultipleOfFive()
        {
            int result = 0;
            for (int i = 0; i < 1000; i++)
            {
                if (i % 5 == 0)
                {
                    result = result + i;
                }
            }
            return result;
        }


The problem here is that if you add those two numbers, it does not give the correct result.

I then tried to do the same thing but put those two subproblems into one:
        //the real method of doing the calculation
        private static int MultipleOfFiveThree()
        {
            int result = 0;
            for (int i = 0; i < 1000; i++)
            {
                if (i % 3 == 0 || i % 5 == 0)
                {
                    result = result + i;
                }
            }
            return result;
        }
 This produces the correct result.

Why is that so? Why is it that when I divide the program into two seperate ways it does not give the correct result?

Ingen kommentarer:

Send en kommentar