Skip to the content.

5 different Fibonacci algorithms

/*
 * Creator: Nighthawk Coding Society
 * Mini Lab Name: Fibonacci sequence, featuring a Stream Algorithm
 * 
*/

import java.util.ArrayList;  
import java.util.HashMap;
import java.util.stream.Stream;

/* Objective will require changing to abstract class with one or more abstract methods below */
abstract class Fibo {
    String name;  // name or title of method
    int size;  // nth sequence
    int hashID;  // counter for hashIDs in hash map
    ArrayList<Long> list;   // captures current Fibonacci sequence
    HashMap<Integer, Object> hash;  // captures each sequence leading to final result

    /*
     Zero parameter constructor uses Telescoping technique to allow setting of the required value nth
     @param: none
     */
    public Fibo() {
        this(8); // telescope to avoid code duplication, using default as 20
    }

    /*
     Construct the nth fibonacci number
     @param: nth number, the value is constrained to 92 because of overflow in a long
     */
    public Fibo(int nth) {
        this.size = nth;
        this.list = new ArrayList<>();
        this.hashID = 0;
        this.hash = new HashMap<>();
        //calculate fibonacci and time mvc
        this.calc();
    }

    /*
     This Method should be "abstract"
     Leave method as protected, as it is only authorized to extender of the class
     Make new class that extends and defines calc()
     Inside references within this class would change from this to super
     Repeat process using for, while, recursion
     */
    protected abstract void calc();

    /*
     Number is added to fibonacci sequence, current state of "list" is added to hash for hashID "num"
     */
    public void setData(long num) {
        list.add(num);
        hash.put(this.hashID++, list.clone());
    }

    /*
     Custom Getter to return last element in fibonacci sequence
     */
    public long getNth() {
        return list.get(this.size - 1);
    }

    /*
     Custom Getter to return last fibonacci sequence in HashMap
     */
    public Object getNthSeq(int i) {
        return hash.get(i);
    }

    /*
     Console/Terminal supported print method
     */
    public void print() {
        System.out.println("Calculation method = " + this.name);
        System.out.println("fibonacci Number " + this.size + " = " + this.getNth());
        System.out.println("fibonacci List = " + this.list);
        System.out.println("fibonacci Hashmap = " + this.hash);
        for (int i=0 ; i<this.size; i++ ) {
            System.out.println("fibonacci Sequence " + (i+1) + " = " + this.getNthSeq(i));
        }
    }
}

For Loop

import java.util.ArrayList;
import java.util.HashMap;

// Define the Fibonacci interface
interface Fibonacci {
    void calc();
    long getNth();
    ArrayList<Long> getSequence();
    HashMap<Integer, Object> getHashMap();
}

// Implement Fibonacci sequence using a for-loop
class FiboForLoop implements Fibonacci {
    private int size;
    private ArrayList<Long> list = new ArrayList<>();
    private HashMap<Integer, Object> hash = new HashMap<>();
    
    public FiboForLoop(int size) {
        this.size = size;
        calc();
    }
    
    public void calc() {
        long[] f = {0, 1};
        for (int i = 0; i < size; i++) {
            list.add(f[0]);
            hash.put(i, new ArrayList<>(list));
            f = new long[]{f[1], f[0] + f[1]};
        }
    }
    
    public long getNth() {
        return list.get(size - 1);
    }
    
    public ArrayList<Long> getSequence() {
        return list;
    }
    
    public HashMap<Integer, Object> getHashMap() {
        return hash;
    }

    public void print() {
        System.out.println("Nth Fibonacci: " + getNth());
        System.out.println("Sequence: " + getSequence());
    }

    public static void main(String[] args) {
        int[] numbers = {2, 5, 8}; // Example input values
        for (int nth : numbers) {
            Fibonacci fib = new FiboForLoop(nth);
            ((FiboForLoop) fib).print();
            System.out.println();
        }
    }
}
FiboForLoop.main(null);
Nth Fibonacci: 1
Sequence: [0, 1]

Nth Fibonacci: 3
Sequence: [0, 1, 1, 2, 3]

Nth Fibonacci: 13
Sequence: [0, 1, 1, 2, 3, 5, 8, 13]

While Loop

import java.util.ArrayList;
import java.util.HashMap;

// Define the Fibonacci interface
interface Fibonacci {
    void calc();
    long getNth();
    ArrayList<Long> getSequence();
    HashMap<Integer, Object> getHashMap();
}

// Implement Fibonacci sequence using a while-loop
class FiboWhileLoop implements Fibonacci {
    private int size;
    private ArrayList<Long> list = new ArrayList<>();
    private HashMap<Integer, Object> hash = new HashMap<>();
    
    public FiboWhileLoop(int size) {
        this.size = size;
        calc();
    }
    
    public void calc() {
        long f0 = 0, f1 = 1;
        int i = 0;
        
        while (i < size) {
            list.add(f0);
            hash.put(i, new ArrayList<>(list));

            long temp = f0 + f1;
            f0 = f1;
            f1 = temp;
            i++;
        }
    }
    
    public long getNth() {
        return list.get(size - 1);
    }
    
    public ArrayList<Long> getSequence() {
        return list;
    }
    
    public HashMap<Integer, Object> getHashMap() {
        return hash;
    }

    public void print() {
        System.out.println("Nth Fibonacci: " + getNth());
        System.out.println("Sequence: " + getSequence());
    }

    public static void main(String[] args) {
        int[] numbers = {2, 5, 8}; // Example input values
        for (int nth : numbers) {
            Fibonacci fib = new FiboWhileLoop(nth);
            ((FiboWhileLoop) fib).print();
            System.out.println();
        }
    }
}

FiboWhileLoop.main(null);
Nth Fibonacci: 1
Sequence: [0, 1]

Nth Fibonacci: 3
Sequence: [0, 1, 1, 2, 3]

Nth Fibonacci: 13
Sequence: [0, 1, 1, 2, 3, 5, 8, 13]

Stream

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

// Define the Fibonacci interface
interface Fibonacci {
    void calc();
    long getNth();
    ArrayList<Long> getSequence();
    HashMap<Integer, Object> getHashMap();
}

// Implement Fibonacci sequence using Stream
class FiboStream implements Fibonacci {
    private int size;
    private ArrayList<Long> list = new ArrayList<>();
    private HashMap<Integer, Object> hash = new HashMap<>();

    public FiboStream(int size) {
        this.size = size;
        calc();
    }

    public void calc() {
        list = Stream.iterate(new long[]{0, 1}, f -> new long[]{f[1], f[0] + f[1]})
                .limit(size)
                .map(f -> f[0])
                .collect(Collectors.toCollection(ArrayList::new));

        for (int i = 0; i < list.size(); i++) {
            hash.put(i, new ArrayList<>(list.subList(0, i + 1)));
        }
    }

    public long getNth() {
        return list.get(size - 1);
    }

    public ArrayList<Long> getSequence() {
        return list;
    }

    public HashMap<Integer, Object> getHashMap() {
        return hash;
    }

    public void print() {
        System.out.println("Nth Fibonacci: " + getNth());
        System.out.println("Sequence: " + getSequence());
    }

    public static void main(String[] args) {
        int[] numbers = {2, 5, 8}; // Example input values
        for (int nth : numbers) {
            Fibonacci fib = new FiboStream(nth);
            ((FiboStream) fib).print();
            System.out.println();
        }
    }
}
FiboStream.main(null);
Nth Fibonacci: 1
Sequence: [0, 1]

Nth Fibonacci: 3
Sequence: [0, 1, 1, 2, 3]

Nth Fibonacci: 13
Sequence: [0, 1, 1, 2, 3, 5, 8, 13]

Recurssion

import java.util.*;

interface Fibonacci {
    void calc();
    long getNth();
    ArrayList<Long> getSequence();
    HashMap<Integer, Object> getHashMap();
}

// Implement Fibonacci sequence using Recursion
class FiboRecursive implements Fibonacci {
    private int size;
    private ArrayList<Long> list = new ArrayList<>();
    private HashMap<Integer, Object> hash = new HashMap<>();

    public FiboRecursive(int size) {
        this.size = size;
        calc();
    }

    // Recursive Fibonacci function
    private long fib(int n) {
        if (n <= 1) return n;
        return fib(n - 1) + fib(n - 2);
    }

    public void calc() {
        for (int i = 0; i < size; i++) {
            list.add(fib(i));
            hash.put(i, new ArrayList<>(list));
        }
    }

    public long getNth() {
        return list.get(size - 1);
    }

    public ArrayList<Long> getSequence() {
        return list;
    }

    public HashMap<Integer, Object> getHashMap() {
        return hash;
    }

    public void print() {
        System.out.println("Nth Fibonacci: " + getNth());
        System.out.println("Sequence: " + getSequence());
    }

    public static void main(String[] args) {
        int[] numbers = {2, 5, 8}; // Example input values
        for (int nth : numbers) {
            Fibonacci fib = new FiboRecursive(nth);
            ((FiboRecursive) fib).print();
            System.out.println();
        }
    }
}
FiboRecursive.main(null);
Nth Fibonacci: 1
Sequence: [0, 1]

Nth Fibonacci: 3
Sequence: [0, 1, 1, 2, 3]

Nth Fibonacci: 13
Sequence: [0, 1, 1, 2, 3, 5, 8, 13]

Dynamic Programming

import java.util.*;

interface Fibonacci {
    void calc();
    long getNth();
    ArrayList<Long> getSequence();
    HashMap<Integer, Object> getHashMap();
}

class FiboDP implements Fibonacci {
    private int size;
    private ArrayList<Long> list = new ArrayList<>();
    private HashMap<Integer, Object> hash = new HashMap<>();

    public FiboDP(int size) {
        this.size = size;
        calc();
    }

    public void calc() {
        long[] dp = new long[size];
        if (size > 0) dp[0] = 0;
        if (size > 1) dp[1] = 1;

        for (int i = 2; i < size; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }

        for (long num : dp) list.add(num);
        for (int i = 0; i < size; i++) {
            hash.put(i, new ArrayList<>(list));
        }
    }

    public long getNth() {
        return list.get(size - 1);
    }

    public ArrayList<Long> getSequence() {
        return list;
    }

    @Override
    public HashMap<Integer, Object> getHashMap() {
        return hash;
    }

    public void print() {
        System.out.println("Nth Fibonacci: " + getNth());
        System.out.println("Sequence: " + getSequence());
    }

    public static void main(String[] args) {
        Fibonacci fib = new FiboDP(10);
        ((FiboDP) fib).print();
    }
}
FiboDP.main(null);
Nth Fibonacci: 34
Sequence: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]