Euler Project: Problem 2

Problem description:

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. https://projecteuler.net/problem=2

Problem solutions:

  1. First naive solution of this problem took about 85 mills:
import java.util.ArrayList;
import java.util.List;

public class Problem_2 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);

for (int i = 2; ; i++) {
int element = list.get(i - 1) + list.get(i - 2);
if (element >= 4_000_000) {
break;
}
list.add(element);
}

System.out.println(
list.stream()
.filter(i -> i % 2 == 0)
.mapToInt(i -> i).sum());

long estimatedTime = System.currentTimeMillis() - startTime;
System.out.println(String.format("Calculations took %d mills", estimatedTime));
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s