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.

Project Euler Problem 2

Here is a more general approach to it that lets us choose if we want the sum of odd or even numbers:

#=
# 
# Generalized Solution of Project Euler problem No. 2
#
# Input:
# 	N := highest number a Fibonacci term should have (default 4000000)
# 	Property := "even" or "odd" numbers that should be summed up (default "even")
#
# Output:
# 	Sum of all even or odd numbers of a Fibonacci sequence with the highest number <= N
#
=#


function getFibonacciTerm(n::UInt64,lastTwoFibonacciTerms::Array{UInt64,1})
	if n <= 2
		lastTwoFibonacciTerms[1] = 1;
		lastTwoFibonacciTerms[2] = 1;
	else
		tmpFTprev2 = lastTwoFibonacciTerms[2];
		lastTwoFibonacciTerms[2] = lastTwoFibonacciTerms[1];
		lastTwoFibonacciTerms[1] = lastTwoFibonacciTerms[2] + tmpFTprev2;
	end
	return lastTwoFibonacciTerms
end

function checkEvenOdd(FibonacciTerm::UInt64,Property::String)
	if Property == "even"
		return iseven(FibonacciTerm)
	else
		return isodd(FibonacciTerm)
	end
end

function ProjectEuler0002(N::UInt64, Property::String)
	n::UInt64 = 1;
	SumofFibonacciTerms::UInt64 = 0;
	lastTwoFibonacciTerms::Array{UInt64,1} = [0;0];
	while lastTwoFibonacciTerms[2] <= N
		lastTwoFibonacciTerms = getFibonacciTerm(n,lastTwoFibonacciTerms);
		n += 1;
		if checkEvenOdd(lastTwoFibonacciTerms[1],Property)
			SumofFibonacciTerms += lastTwoFibonacciTerms[1];
		end
	end
	return SumofFibonacciTerms
end

function parseARGS()
	if isempty(ARGS)
		N::UInt64 = 4000000;
		Property::String = "even";
	else
		N = tryparse(UInt64,ARGS[1]);
		Property = ARGS[2];
	end
	return N, Property
end

function main()
	N, Property = parseARGS();
	result = ProjectEuler0002(N, Property);
	println(result)
end


julia 0002/ProjectEuler0002.jl

4613732

julia 0002/ProjectEuler0002.jl 10 even

10

julia 0002/ProjectEuler0002.jl 10 odd

44