All pastes #1558995 Raw Edit

Euler 2

public java v1 · immutable
#1558995 ·published 2009-09-08 22:28 UTC
rendered paste body
		Benchmark benchmark = new Benchmark();		BigInteger upperBound = new BigInteger(args[0]);		BigInteger total = BigInteger.ZERO;		BigInteger two = BigInteger.valueOf(2);		Map<BigInteger, BigInteger> cache = new TreeMap<BigInteger, BigInteger>();		BigInteger curTermNumber = BigInteger.ONE, curTerm;		while ((curTerm = fibonacci(curTermNumber, cache)).compareTo(upperBound) <= 0) {			if (curTerm.mod(two).equals(BigInteger.ZERO))				total = total.add(curTerm);			curTermNumber = curTermNumber.add(BigInteger.ONE);		}		Display.time(benchmark.end());		Display.answer(total);// Support code:	public static BigInteger fibonacci(BigInteger termNumber, Map<BigInteger, BigInteger> cache) {		if (termNumber.compareTo(BigInteger.ONE) < 0)			throw new IllegalArgumentException("invalid Fibonacci sequence term number:" + termNumber);		else if (termNumber.compareTo(BigInteger.ONE) == 0)			return BigInteger.ZERO;		else if (termNumber.compareTo(BigInteger.valueOf(2)) == 0)			return BigInteger.ONE;		else {			BigInteger result = cache.get(termNumber);			if (result != null)				return result;			result = fibonacci(termNumber.subtract(BigInteger.valueOf(2)), cache).add(fibonacci(termNumber.subtract(BigInteger.ONE), cache));			cache.put(termNumber, result);			return result;		}	}