programming language is JAVA: Write a public static method named static long fib
ID: 3841174 • Letter: P
Question
programming language is JAVA:
Write a public static method named static long fibFast(int n, long a, long b)
that returns the nth fibonacci number. The method should be coded as follows:
If n is zero then just return a (the zeroth fibonacci number).
If n > 0 call the function recursively with n-1 as the first parameter , b as the second parameter and a+b as the last parameter .
Effecfively, we are creating a loop in which a and b represent two consecutive fibonacci numbers. As n goes down by 1 we replace those by the next consecutive pair of Fibonacci numbers.
Eventually n reaches 0 and the first parameter will equal the nth fibonacci number.
Note: this only works if the initial call is fibFast(n, 0, 1).
Explanation / Answer
please find the method
static long fibFast(int n, long a, long b){
if(n==0)
return a;
else
return fibFast(n-1,b,a+b);
}
and whole runnng code is
import java.util.Scanner;
public class Program {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of n ");
int num = sc.nextInt();
long number = fibFast(num,0,1);
System.out.println("nth fibonacci number is "+number);
}
static long fibFast(int n, long a, long b){
if(n==0)
return a;
else
return fibFast(n-1,b,a+b);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.