Skip to content

Instantly share code, notes, and snippets.

@ChrisLeNeve
Created September 30, 2019 11:24
Show Gist options
  • Save ChrisLeNeve/0a1f371141fedb7b5f9b2302bbe9e5c8 to your computer and use it in GitHub Desktop.
Save ChrisLeNeve/0a1f371141fedb7b5f9b2302bbe9e5c8 to your computer and use it in GitHub Desktop.
projecteuler problem 2
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;
}
}
@ChrisLeNeve
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment