четверг, 17 января 2008 г.

Ударим LINQом по Project Eiler

Задача 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.


Решение.

static void eiler1(){
Console.WriteLine((from i in Enumerable.Range(0, 1000) where (i % 3 == 0) || (i % 5 == 0) select i).Sum());
}


такие дела.

Задача 2:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed one million.


Решение (понадобилась дополнительная функция)

using System;
using System.Linq;
using System.Collections.Generic;

namespace eiler{
class Program
{
public static IEnumerable fibonator(int max){
int prev = 1;
int curr = 2;
while (true){
yield return curr;
int nprev = prev + curr;
curr += nprev;
prev = nprev;
if (curr >= max)
yield break;

}
}
static void Main(string[] args){
Console.WriteLine(
(from i in fibonator(1000000) select i).Sum() );
}
}
}

Комментариев нет: