3 Fibonacci numbers (30 points) The Fibonacci sequence is a famous mathematical
ID: 3742787 • Letter: 3
Question
3 Fibonacci numbers (30 points) The Fibonacci sequence is a famous mathematical sequence where each successive term is the sum of the two preceding ones. This can be expressed mathematically as F - -1 Fn-2, where Fi 1 and F21. The sequence, therefore, goes 1, 1, 2 (1+1), 3 (1+2), 5 (2+3), 8 (3+5 13 (5+8), 21, 34, 55, 89, 144.. Write a program called Fib.java which allows a user to entera number n as a command-line argument. The program will print out the nth Fibonacci number Hint: you will have to change the argument in the variable arg[0 from a String to an int using Integer.parselnt ) s java Fib 4 $ java Fib 7 13 s java Fib 11 89Explanation / Answer
public class Fib { public static int fib(int n) { if(n == 1 || n == 2) { return 1; } else { return fib(n-1) + fib(n-2); } } public static void main(String[] args) { if(args.length > 0) { int n = Integer.parseInt(args[0]); System.out.println(fib(n)); } } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.