online advertising

Friday, August 16, 2013

Problem 1: Multiples of 3 and 5

Problem:

Please find the problem here.

Solution:

Hey, don't complicate it. You don't need any mathematics for this simple problem. Just brute force will get you answer in less than a second.

namespace Euler
{
    using System;

    internal static partial class Program
    {
        public static void Problem001()
        {
            int sum = 0;
            for (int i = 1; i < 1000; i++)
            {
                if (i % 3 == 0 || i % 5 == 0)
                {
                    sum += i;
                }
            }
            Console.WriteLine(sum);
        }
    }
}

Of course, there are better method. But in my humble opinion, it is not worth the effort, but it is a good learning exercise anyway. In order to compute the sum of the number that is either a multiple of 3 or multiple of 5, we could use the inclusion-exclusion principle simplified as follow:

The sum of the numbers in A union B is the sum of numbers in A + the sum of numbers in B - the sum of numbers in A intersect B.

Applying the rule to our case, we have:
The sum of multiples of 3 less than 1000 is $ \sum\limits_{i=1}^{\lfloor \frac{1000}{3} \rfloor}3i = 166833 $.
The sum of multiples of 5 less than 1000 is $ \sum\limits_{i=1}^{\lfloor \frac{1000}{5} \rfloor}5i = 99500 $.

The sum of multiples of 15 less than 1000 is $ \sum\limits_{i=1}^{\lfloor \frac{1000}{15} \rfloor}15i = 33165 $

The final answer is 166833 + 99500 - 33165 = 233168.

Answer: 233168

No comments :

Post a Comment