8.27.2012

Project Euler Problem 1: Find the sum of all the multiples of 3 or 5 below 1000

Problem 1: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

The answer is 233168.

The first solution I had was straight forward: check the reminder of each number below 1000 and added it to Sum if it's multiples of 3 or 5.
            int Sum = 0;

            for (int x = 1; x < 1000; x++)
            {
                if (x % 3 == 0) Sum += x;
                else if (x % 5 == 0) Sum += x;
                Console.WriteLine("x = {0}, sum = {1}", x, Sum);
            }
Another solution is using the formula (1+2+3+....+n) = (1+n)n/2
Once we find the largest number, we can use this formula to calculate the sum:
 
           int sumOf3 = 0;
            int sumOf5 = 0;
            int sumOf15 = 0;

            for (int i = 999; i > 0; i--)
            {
                if (i % 3 == 0)
                {
                    sumOf3 = (3 + i) * (i / 3) / 2; //remember to start with 3
                    break;
                }
            }

            for (int j = 999; j > 0; j--)
            {
                if (j % 5 == 0)
                {
                    sumOf5 = (5 + j) * (j / 5) / 2; //remember to start with 5
                    break;
                }
            }


            for (int k = 999; k > 0; k--)
            {
                if (k % 15 == 0)
                {
                    sumOf15 = (15 + k) * (k / 15) / 2; //remember to start with 15
                    break;
                }
            }

            Console.WriteLine("Sum of 3 = {0}", sumOf3);
            Console.WriteLine("Sum of 5 = {0}", sumOf5);
            Console.WriteLine("Sum of 15 = {0}", sumOf15);
            Console.WriteLine("Solution = {0}", sumOf3 + sumOf5 - sumOf15);

No comments:

Post a Comment