Anda di halaman 1dari 1

AP Computer Science Java: Recursion Quiz – Computer Portion

The so-called Fibonacci sequence is a series of numbers that begins with 1, 1, 2, 3, 5, …. After
the first two ones, each number is determined by adding the previous two (2=1+1, 3=2+1, etc…).

In mathematical notation, the sequence is defined as follows:

For n=1 and n=2: Fn=1 (i.e., F1=1 and F2=1)


For n>2: Fn = Fn-1 + Fn-2

For example,

F3 = F2 + F1, so F3 = 1 + 1 = 2

and

F4 = F3 + F2, so F4 = 2 + 1 = 3.

Your task:

1. Write a recursive method, using the heading below, to generate the nth Fibonacci
number.
2. Use this method in a program to generate the first n Fibonacci numbers, with n defined
by the user.

For example, if the user inputs 6, the output will be: 1, 1, 2, 3, 5, 8

The header for the recursive method should be as follows:

public static int fib(int n)

Anda mungkin juga menyukai