Wednesday 14 October 2015

Project Euler #1: Multiples of 3 and 5

Hi guys, today I will show you how to solve Project Euler Problem 1, the question is
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 1000000000.

I tried to solve this question using for loop. It was working fine but it was taking so many times to get the result. Then I implemented some mathematical logic to solve this issue.


static void Main(String[] args) {
            int i = Convert.ToInt32(Console.ReadLine());
            List<long> list = new List<long>();
            for (int j = 0; j < i; j++)
            {
                list.Add(Convert.ToInt64(Console.ReadLine()));
            }
            foreach(long k in list)
            {
                long sum=0;
                long i3 = (((k - 1) / 3) * (((k - 1) / 3) + 1)) / 2;
                sum += i3 * 3;
                long i5 = (((k - 1) / 5) * (((k - 1) / 5) + 1)) / 2;
                sum += i5 * 5;
                long i15 = (((k - 1) / 15) * (((k - 1) / 15) + 1)) / 2;
                sum -= i15 * 15;
                Console.WriteLine(sum);
            }
    }

No comments:

Post a Comment