Skip to content

Instantly share code, notes, and snippets.

@shout-poor
Created September 12, 2015 11:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shout-poor/7bc5ca7f774ece9352a4 to your computer and use it in GitHub Desktop.
Save shout-poor/7bc5ca7f774ece9352a4 to your computer and use it in GitHub Desktop.
Java8のStreamAPIでフィボナッチ関数
import java.math.BigInteger;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
import static java.math.BigInteger.*;
public class Fibonacci implements UnaryOperator<BigInteger> {
@Override
public BigInteger apply(BigInteger n) {
assert(n != null && n.compareTo(ZERO) >= 0);
return Stream.iterate(new BigInteger[] { ZERO, ZERO, ZERO }, cont -> {
BigInteger x = cont[0].add(ONE);
BigInteger preY = cont[1];
BigInteger y = (x.equals(ZERO)||x.equals(ONE)) ? x : cont[1].add(cont[2]);
return new BigInteger[] {x, y, preY};
})
.filter(cont -> cont[0].equals(n))
.findFirst()
.map(cont -> cont[1])
.orElseThrow(() -> new RuntimeException("Failed."));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment