Project Euler in PL/SQL: Problem 2

  • by

Time for my second entry in the Project Euler series. A bit more to keep track of this time, but still pretty simple.

Problem 2:

Even Fibonacci Numbers

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.

upper_limit INTEGER := 4000000;
answer INTEGER := 0;
a INTEGER := 1;
b INTEGER := 2;
c INTEGER := 0; --must declare an initial value; NULL !< any number
    WHILE c < upper_limit
        c := a + b;
        --check if number is even
        IF REMAINDER(b,2) = 0
            answer := answer + b;
        END IF;
        a := b;
        b := c;


-- output: 4613732

Another straight forward solution here. You could create a function to return the next value in the sequence, and another to return if a number is even or not, but I think it’s perfectly readable the way it is now.

Questions or comments? Feel free to leave them below or reach out to me on Twitter!

Leave a Reply

Your email address will not be published.