HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Project Euler #2 Efficiency

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
projectefficiencyeuler

Problem

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 N, find the sum of the even-valued terms.

I'd like to reduce the complexity of my code.

import java.math.BigInteger;
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int testCases = sc.nextInt();
        for (int i = 0; i 0) {

            if (fib.doubleValue() % 2 == 0)
                sum = sum.add(fib);
            fib = fib1.add(fib2);
            fib1 = fib2;
            fib2 = fib;

        }

        return sum;
    }

}

Solution

The test

if (fib.doubleValue() % 2 == 0)


does not produce the correct result for numbers with more than 17 digits, because
that exceeds the precision of a double. Actually it returns true for 8944394323791464 and all subsequent Fibonacci numbers.
That is not relevant for the concrete problem here (see below), but if you want to work with BigInteger then you should replace this with

if (fib.remainder(bigTwo).equals(BigInteger.ZERO))


where bigTwo is defined as

BigInteger bigTwo = new BigInteger("2");


Project Euler Problem #2
asks for the sum of all even-valued Fibonacci values not exceeding 4 million,
so using BigInteger is not really necessary. All numbers fit into the range
of int, and the above test simplifies to

if (fib % 2 == 0)


(I also planned to tell that using int instead of BigInteger makes the
program more efficient, but it turned out that the difference in running
time is not significant.)

Code Snippets

if (fib.doubleValue() % 2 == 0)
if (fib.remainder(bigTwo).equals(BigInteger.ZERO))
BigInteger bigTwo = new BigInteger("2");
if (fib % 2 == 0)

Context

StackExchange Code Review Q#67188, answer score: 8

Revisions (0)

No revisions yet.