Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Fibonacci implements Iterator<BigInteger> {
- private final AtomicReference<BigInteger> prev = new AtomicReference<>(ZERO);
- private final AtomicReference<BigInteger> curr = new AtomicReference<>(ONE);
- public boolean hasNext() {
- return true;
- }
- public BigInteger next() {
- while (true) {
- var prev = this.prev.get();
- var curr = this.curr.get();
- var nextCurr = ZERO == prev ? new BigInteger("1") : curr.add(prev);
- if (prev != curr && this.prev.get() == prev) {
- if (this.prev.compareAndSet(prev, curr)) {
- this.curr.compareAndSet(curr, nextCurr);
- return nextCurr;
- } else {
- this.curr.compareAndSet(curr, nextCurr);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement