domingo, 8 de maio de 2016

Resposta do problema 002 - Even Fibonacci numbers

O segundo problema do site project euler faz uso da série de Fibonacci. O problema pede para somarmos todos os números da série de fibonacci menores que 4000000 (milhoes) e que sejam par.
Even Fibonacci numbers
Problem 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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Link para a pergunta: https://projecteuler.net/problem=2

Criei o seguinte script para resolver o problema:
a = 1
b = 1
x = 0
soma = 0
while x < 4000000:
 x = a + b
 if x % 2 == 0:
  soma = soma + x
 a = b
 b = x

print(soma)

Resposta (answer) - Selecione a linha abaixo para ver a resposta
4613732

Outras respostas postadas por outros usuários no fórum:
Usuário bael2212
class FibSequence:
    def __init__(self, endp):
        self.end = endp

    def fibtomax(self):
        fib1 = 0
        fib2 = 1
        fib3 = fib1 + fib2
        fibseq = []
        fibseq.append(fib3)
        fibeven = []
        while fib3 < self.end:
            fib1 = fib2
            fib2 = fib3
            fib3 = fib1 + fib2
            fibseq.append(fib3)
        for i in fibseq:
            if i % 2 == 0:
                fibeven.append(i)
        return sum(fibeven)

obj2 = FibSequence(4000000)

print obj2.fibtomax()

Usuário KaiserK
def even_fibs(n):
    a, b = 0, 2

    while b < n:
        a, b = b, 4 * b + a

    return (a + b - 2) / 4


print even_fibs(4000000)

Nenhum comentário:

Postar um comentário