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.
Solution
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Project Euler 002</title>
</head>
<body >
<script type="text/javascript">
answer = 0;
fib0 = 1;
fib1 = 1;
fib2 = 2;
while (fib2 < 4000000)
{
answer += fib2;
fib0 = fib1 + fib2;
fib1 = fib0 + fib2;
fib2 = fib0 + fib1;
}
document.write("<b>" + answer + "</b>");
</script>
</body>
</html>
Discussion
C based languages have such similar syntax that this is a copy from the C# solution. Of course, I had to remove the type declarations because it’s not strongly typed. Oh, and I guess I do output to HTML.
If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).
Leave a Reply