I need a formal algorithm for the following question The Fib
I need a formal algorithm for the following question
The Fibonacci numbers are defined by the sequence:
f1 = 1
f2 = 1
fn = fn-1 + fn-2.
Reformulate that as
Fold1 = 1;
Fold2=1;
Fnew=fold1+fold2;
After that, discard fold2, which is no longer needed, and set fold2 to fold1, and fold1 to fnew. Repeat an appropriate number of times.
Implement a program that prompts the user for an integer n and prints the nth Fibonacci number, using the above algorithm.
Solution
/*
Algorithm :
Input : Get the number n from the user.
n denotes the nth number in fibonacci sequence.
the first 2 numbers of fibonacci sequence is 1.
So, if n is less than or equal to 2 and greater than equal to 1
then return 1.
else
assign the first two numbers to
fold1 = 1
fold2 = 1
Since we have two numbers we need to run the loop from n to 2
within the loop will calculate the next number using below assignment
fnew = fold1+fold2
For the next iteration fnew will be the last number and fold2 will be the second last number hence
use below statements to assign fold1 and fold2 properly for next iteration
fold1 = fold2
fold2 = fnew;
Once the loop ends return the fnew
*/
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Fibonacci {
public static int getNthFibonacciNumber(int n)
{
int fold1 = 1,fold2 = 1;
int fnew = 1;
while(n>2)
{
fnew = fold1+fold2;
fold1 = fold2;
fold2 = fnew;
n--;
}
return fnew;
}
public static void main(String[] args)
{
int n;
System.out.println(\"Input n:\");
Scanner input = new Scanner(System.in);
n = input.nextInt();
System.out.println(n + \"th fibonacci number is : \"+getNthFibonacciNumber(n));
}
}
OUTPUT:
run:
Input n:
5
5th fibonacci number is : 5
BUILD SUCCESSFUL (total time: 2 seconds)
