http://projecteuler.net/index.php?section=problems&id=2Each 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 four million.
My solution is behind the cut. In FORTRAN, of course.
( Read more... )Not having an easy way in FORTRAN (that I know of, anyway) to see if one number cleanly divides another, I had to implement a kludge to solve this problem. First I have two temporary variables, one is a real and the other an integer. To test if something is even or not, I divide by 2. I do this once with the real, and once with the integer. Integer math in FORTRAN of course always returns a number without any decimals. So "tempint = FibTemp/2" always returns some nice round number. Doing real number math with "tempreal = FibTemp/2.0" will return either a round number with a lot of trailing .0000's or some number like 2.5. Fortunately the conditional doesn't care if it's comparing a REAL or an INT together, unlike more advanced languages where types are a big issue, so it says that "2" and "2.0000000000" are the same number. So therefore if these two temporary variables are equal, then our Fibonacci number is an even number.
I'm not going to go into the wonders of Fibonacci numbers here, but suffice it to say that they're pretty cool and actually sometimes important in Mathematics, Geometry, and Architecture. The Wikipedia page on
Fibonacci numbers is a fairly nice introduction to the topic.