Respuesta :
Answer:
The Python Code for Fibonacci Sequence is :
# Function for nth Fibonacci number
def Fibonacci(n):
if n<0:
print("Incorrect input")
# First Fibonacci number is 0
elif n==0:
return 0
# Second Fibonacci number is 1
elif n==1:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
# Driver Program
print(Fibonacci(9))
Explanation:
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.
Answer:
//import the Scanner class
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
//create an object of the Scanner class
Scanner input = new Scanner(System.in);
//Prompt the user to enter the number of terms
System.out.println("Enter the number of terms");
//Store the user input in a variable
int noOfTerms = input.nextInt();
//Create a variable sum to hold the sum of the series.
int sum = 0;
//Display message
System.out.println("First " + noOfTerms + " terms of Fibonacci numbers are");
//Create a loop that goes as many times as the number of terms
//At every term (cycle), call the fibonacci method on the term.
//And add the number to the sum variable
for (int i = 1; i<=noOfTerms; i++){
System.out.println(fibonacci(i));
sum += fibonacci(i);
}
//Display a message
System.out.println("The sum of the above sequence is ");
//Display the sum of the fibonacci series
System.out.println(sum);
}
//Create a method fibonacci to return the nth term of the fibonacci series
public static int fibonacci(int n){
//when n = 1, the fibonacci number is 0
if (n <= 1){
return 0;
}
//when n = 2, the fibonacci number is 1
else if(n == 2){
return 1;
}
//at other terms, fibonacci number is the sum of the previous two numbers
else {
return fibonacci(n-1) + fibonacci(n-2);
}
} // End of fibonacci method
} // End of class declaration
Sample Output:
>> Enter the number of terms
7
>> First 7 terms of Fibonacci numbers are
0
1
1
2
3
5
8
>> The sum of the above sequence is
20
Explanation:
The above code has been written in Java. It contains comments explaining important parts of the code. Please go through the code through the comments for understandability.