DEV Community

Mustafa  Çam
Mustafa Çam

Posted on

fibonacci

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class fibonacci {
    private int previous=0;
    private int next=1;

    private List<Integer> list = new ArrayList<>(Arrays.asList(previous, next));
    public List<Integer> fibonaccii(int a){

        if(a<0){
            throw new IllegalArgumentException("a must be greater than 0");
        }
        if (a < 2) {
            return list.subList(0, a);
        }

         int sum;
        for(int i=2;i<=a;i++){
            sum=previous+next;
            list.add(sum);
            previous=next;
            next=sum;
        }
            return list;
    }


public static void main(String[] args) {
    System.out.println("Try programiz.pro");
    fibonacci f = new fibonacci();
    List<Integer> result = f.fibonaccii(5);

    System.out.println(result);
}
}
Enter fullscreen mode Exit fullscreen mode

javac fibonacci.java
java fibonacci.java

out:
Try programiz.pro
[0, 1, 1, 2, 3, 5]

Top comments (0)