Answers for "fibonacci code"

10

fibonacci

# WARNING: this program assumes the
# fibonacci sequence starts at 1
def fib(num):
	"""return the number at index `num` in the fibonacci sequence"""
    if num <= 2:
        return 1
    return fib(num - 1) + fib(num - 2)

# method 2: use `for` loop
def fib2(num):
	a, b = 1, 1
	for _ in range(num - 1):
		a, b = b, a + b
	return a


print(fib(6))  # 8
print(fib2(6))  # same result, but much faster
Posted by: Guest on February-24-2020
10

fibonacci

# Easy fibonacci exercise
# Method #1
def fibonacci(n):
    # 1th: 0
    # 2th: 1
    # 3th: 1 ...
    if n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

# Method #2
def fibonacci2(n):
    if n == 0: return 0
    n1 = 1
    n2 = 1
    # (1, n - 2) because start by 1, 2, 3... not 0, 1, 1, 2, 3....
    for i in range(1, n - 2):
        n1 += n2
        n2 = n1 - n2
    return n1


print(fibonacci(13))
# return the nth element in the fibonacci sequence
Posted by: Guest on January-01-2021
5

fibonacii sequence code

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms
n1, n2 = 0, 1
count = 0

# check if the number of terms is valid
if nterms <= 0:
   print("Please enter a positive integer")
elif nterms == 1:
   print("Fibonacci sequence upto",nterms,":")
   print(n1)
else:
   print("Fibonacci sequence:")
   while count < nterms:
       print(n1)
       nth = n1 + n2
       # update values
       n1 = n2
       n2 = nth
       count += 1
Posted by: Guest on May-12-2020
1

fibinachi

def fib(n):
  lisp = []
  
  for i in range(n):
    if len(lisp) < 3:
      if len(lisp) == 0:
        lisp.append(0)
      else:
        lisp.append(1)
    
    else:
      lisp.append(lisp[len(lisp)-1]+lisp[len(lisp)-2])
  
  return lisp
Posted by: Guest on October-13-2020
0

Fibonacci

import java.util.Scanner;
public class Fibonacci 
{
    public static void main(String[] args) 
    {
        int n, a = 0, b = 0, c = 1;
        Scanner s = new Scanner(System.in);
        System.out.print("Enter value of n:");
        n = s.nextInt();
        System.out.print("Fibonacci Series:");
        for(int i = 1; i <= n; i++)
        {
            a = b;
            b = c;
            c = a + b;
            System.out.print(a+" ");
        }
    }
}
Posted by: Guest on June-13-2021
0

fibonacci

fib(5)   
                     /                  
               fib(4)                fib(3)   
             /                      /     
         fib(3)      fib(2)         fib(2)    fib(1)
        /             /           /      
  fib(2)   fib(1)  fib(1) fib(0) fib(1) fib(0)
  /    
fib(1) fib(0)
Posted by: Guest on June-11-2021

Python Answers by Framework

Browse Popular Code Answers by Language