Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

java - Fibonacci Series - using for loop - new idea

I have coded fibonacci series using java language , and finished with this solution, how it appears and is that a better solution ?

 static int loopFibonacci(int num) {
        if(num <1) {
            throw new IllegalArgumentException("this number is not valid for fibonacci series");
        }
        int sum = 1;
        int prev = 0;
        for (int i=1;i<num;i++) {
            sum+=prev;
            prev = sum-prev;
//            System.out.println("sum="+sum+" , prev = "+prev);
        }
        return sum;
    }
}

`
   

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The goodness of algorithm generally is defined by some factors like how fast it is, and how easy it is to understand.

Let me share the easiest code for calculating fibonaci:

private int fibonaci(int n) {
    if (n < 3) return 1;
    return fibonaci(n-1) + fibonaci(n-2);
}

But this is exponential with O(2^n) time complexity. Your algorithm has O(n) time complexity which is much much better than exponential.

There is even better algorithm to calculate n-th fibonaci number though and it has O(logn) time complexity. You can find it here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...