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]

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay