Java Program Fibonacci Sequence

前端 未结 15 1878
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 03:17

I am writing a \"simple\" program to determine the Nth number in the Fibonacci sequence. Ex: the 7th number in the sequence is: 13. I have finished writing the program, it

15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 03:25

    This is the code in Python, which can easily be converted to C/Java. First one is recursive and second is the iterative solution.

    def fibo(n, i=1, s=1, s_1=0):
        if n <= i: return s
        else: return fibo(n, i+1, s+s_1, s)
    
    
    def fibo_iter_code(n):
        s, s_1 = 1, 0
        for i in range(n-1):
           temp = s
           s, s_1 = s+s_1, temp
           print(s)
    

提交回复
热议问题