Project Euler #1 : Summing all multiples of 3 and 5 below 1000
The first problem in Project Euler requires us to find the sum of multiples of three and five under 1000.
Ignoring theory of arithmetic progression, this problem can be solved easily using loop construction. For each integer under 1000, we check whether the number is a multiple of 3, and if it is, we accumulate the number. We do the same for multiples of 5 and 15. After the loop finishes, the answer to the problem is simply the total of sum of multiples of 3 and sum of multiples of 5, minus the sum of multiples of 15.
We need to minus the sum of multiples of 15 because 15 itself is a multiple of 3 and 5, hence had been counted twice.
The C# source code can be used to calculate the answer. If you see a heavy influence of C imperative programming in the code, that’s just because it’s where I come from. It’s possible to write a one-liner program that does the same in some programming language, but if you’re learning and looking for sharpening your problem solving skill, step-by-step instruction is just fine. Learning the language features and libraries, while necessary, may come later.
using System;
namespace Euler1
{
/* Add the natural numbers below one thousand that are multiples of 3 or 5 */
class Program
{
static void Main(string[] args)
{
int sumMultiplesOf3 = 0;
int sumMultiplesOf5 = 0;
int sumMultiplesOf15 = 0;
int remainder;
int total;
for (int i = 1; i < 1000; i++)
{
Math.DivRem(i,3, out remainder);
if (remainder == 0)
sumMultiplesOf3 += i;
Math.DivRem(i, 5, out remainder);
if (remainder == 0)
sumMultiplesOf5 += i;
Math.DivRem(i, 15, out remainder);
if (remainder == 0)
sumMultiplesOf15 += i;
}
total = sumMultiplesOf3 + sumMultiplesOf5 - sumMultiplesOf15;
Console.WriteLine("Add the natural numbers below one thousand that are multiples of 3 or 5");
Console.WriteLine("Answer is {0}", total);
}
}
}
You may submit the answer to Project Euler website and receive a note of congratulation
.



Trackbacks