Java
Fibonacci
Non-Recursive Solution
Programming
Algorithms

What is a non recursive solution for Fibonacci-like sequence in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A Fibonacci-like sequence starts with two seed values, and every later value is the sum of the previous two. In Java, the most practical way to compute such a sequence is usually iterative, because it is faster, uses constant extra memory, and avoids the call-stack overhead of recursion.

Why Iteration Beats Naive Recursion

The classic recursive Fibonacci implementation is easy to write but inefficient. It recalculates the same values many times, so the running time grows rapidly as n increases. An iterative solution keeps only the last two values and updates them in a loop, which gives linear time and constant space.

For a generalized sequence:

  • term 0 is the first seed
  • term 1 is the second seed
  • every later term is the sum of the previous two terms

Iterative Implementation

The core algorithm is just a loop with three variables.

java
1public final class FibonacciLike {
2    public static long nthTerm(long first, long second, int n) {
3        if (n < 0) {
4            throw new IllegalArgumentException("n must be non-negative");
5        }
6        if (n == 0) {
7            return first;
8        }
9        if (n == 1) {
10            return second;
11        }
12
13        long previous = first;
14        long current = second;
15
16        for (int i = 2; i <= n; i++) {
17            long next = previous + current;
18            previous = current;
19            current = next;
20        }
21
22        return current;
23    }
24
25    public static void main(String[] args) {
26        System.out.println(nthTerm(0, 1, 10)); // 55
27        System.out.println(nthTerm(2, 3, 6));  // 21
28    }
29}

This implementation works for the standard Fibonacci sequence with seeds 0 and 1, but it also handles any Fibonacci-like pair, such as 2 and 3.

Generating the Full Sequence

If you need every term instead of just the nth value, build a list while still using the same iterative logic.

java
1import java.util.ArrayList;
2import java.util.List;
3
4public final class FibonacciSeries {
5    public static List<Long> firstTerms(long first, long second, int count) {
6        if (count < 0) {
7            throw new IllegalArgumentException("count must be non-negative");
8        }
9
10        List<Long> result = new ArrayList<>();
11        if (count == 0) {
12            return result;
13        }
14
15        result.add(first);
16        if (count == 1) {
17            return result;
18        }
19
20        result.add(second);
21        long previous = first;
22        long current = second;
23
24        for (int i = 2; i < count; i++) {
25            long next = previous + current;
26            result.add(next);
27            previous = current;
28            current = next;
29        }
30
31        return result;
32    }
33}

This version is useful for printing, charting, or testing a sequence. The time cost is still linear, but the space cost becomes linear as well because you are storing every value.

Handling Large Values

For larger indices, long will overflow. If that matters, use BigInteger.

java
1import java.math.BigInteger;
2
3public static BigInteger nthBigTerm(BigInteger first, BigInteger second, int n) {
4    if (n == 0) {
5        return first;
6    }
7    if (n == 1) {
8        return second;
9    }
10
11    BigInteger previous = first;
12    BigInteger current = second;
13
14    for (int i = 2; i <= n; i++) {
15        BigInteger next = previous.add(current);
16        previous = current;
17        current = next;
18    }
19
20    return current;
21}

That change preserves correctness for much larger sequence values at the cost of more object allocation.

Choosing the Right Base Cases

Most mistakes in Fibonacci-like code come from indexing, not from the loop itself. Decide clearly whether n is zero-based or one-based. The examples above are zero-based, so n == 0 returns the first seed and n == 1 returns the second seed.

If you switch to one-based indexing, update the base cases and loop bounds consistently. Mixing the two conventions produces off-by-one bugs that look like arithmetic errors.

Common Pitfalls

Naive recursion is often dramatically slower than expected because it recomputes the same subproblems.

Off-by-one indexing errors are common. Define whether the first term is index 0 or index 1 before writing the loop.

Using int or long for very large sequence positions will overflow silently. Use BigInteger if exact large values matter.

Returning only the last value when the caller expects the whole sequence is another common mismatch. Clarify the API contract up front.

Negative n should be rejected early so the method fails predictably.

Summary

  • An iterative loop is the standard non-recursive solution for Fibonacci-like sequences in Java.
  • The algorithm runs in linear time and uses constant extra memory for a single term.
  • A list-based variant is useful when the caller needs every term.
  • Use BigInteger when overflow is a concern.
  • Most bugs come from indexing and base-case mistakes, not from the addition step.

Course illustration
Course illustration

All Rights Reserved.