Created
September 30, 2019 11:24
-
-
Save ChrisLeNeve/0a1f371141fedb7b5f9b2302bbe9e5c8 to your computer and use it in GitHub Desktop.
projecteuler problem 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Set; | |
import java.util.TreeSet; | |
class Scratch { | |
public static void main(String[] args) { | |
long sum = findSolution(); | |
System.out.println(sum); | |
} | |
private static long findSolution() { | |
Set<Integer> fibSeq = populateFibSeqWithMax(4000000); | |
long sum = 0; | |
for (int i : fibSeq) { | |
if (i % 2 == 0) { | |
sum += i; | |
} | |
} | |
return sum; | |
} | |
private static Set<Integer> populateFibSeqWithMax(int max) { | |
Set<Integer> result = new TreeSet<>(); | |
int secondToLast = 1, last = 2; | |
result.add(secondToLast); | |
result.add(last); | |
int currentSum = 1 + 2; | |
while (currentSum <= max) { | |
result.add(currentSum); | |
secondToLast = last; | |
last = currentSum; | |
currentSum = secondToLast + last; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Preferred clarity and reusability over performance here: could have done the even check within the populateFibSequence loop, which would have made the extra loop in findSolution() unnecessary.