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.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Euler
{
class Program
{
//Add all the natural numbers below one thousand that are multiples of 3 or 5.
//0.001 seconds
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
int total = 0;
for (int i = 1; i <>
{
if (i % 3 == 0 || i % 5 == 0)
{
total += i;
}
}
Console.WriteLine("Answer: " + total);
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.WriteLine(sw.ElapsedTicks);
Console.ReadLine();
}
}
}
The F# solution:
F#
#light
//0096404 milliseconds
open System.Diagnostics
let stopWatch = new Stopwatch()
stopWatch.Start()
printfn "%A" (List.sum(List.filter (fun n-> (n % 3) = 0 or (n % 5) = 0) [1 .. 999]))
stopWatch.Stop();
printfn "%A"stopWatch.Elapsed
printfn "%A"stopWatch.ElapsedTicks
open System
Console.ReadKey(true)
C# does it in
0.001 seconds
3606 ticks
F# does it in
0.0096404 seconds
24380 ticks
There is probably some more efficient way of doing the F#, this was however my first attempt at learning the language. Will have to see how it can do the more tougher problems.
for faster performance, don't take the entire list of integers from [1..999], and filter it
ReplyDeleteinstead use a sequence generator for only the values which you require, and sum the sequence
-whizbang