Big_C.585
April 22nd, 2009, 12:55 PM
hey guys i am having trouble writing the constructor for the Fibonacci sequence. i am very confused. for privaste data members the book gave us fold1 and fold2 to use. here is my assignment so you have a better understanding of what i am trying to accomplish. i also will post my code. Write a program that prompts the user for n and prints the nth value in the Fibonacci sequence. Use a class FibonacciGenerator with a method nextNumber .
There is no need to store all values for fn. You only need the last two values to compute the next one in the series:
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 .
public class FibonacciGenerator
{
public static int fib(int n)
{
int fold1=0, fold2=1;
public getNumber()
for(int i=0; i<n; i++)
{
int savefold1 = fold1;
fold1 = fold2;
fold2 = savefold1 + fold2;
}
return fold1;
}
}
i have no clue if im even on the right track so any help is much appreciated
There is no need to store all values for fn. You only need the last two values to compute the next one in the series:
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 .
public class FibonacciGenerator
{
public static int fib(int n)
{
int fold1=0, fold2=1;
public getNumber()
for(int i=0; i<n; i++)
{
int savefold1 = fold1;
fold1 = fold2;
fold2 = savefold1 + fold2;
}
return fold1;
}
}
i have no clue if im even on the right track so any help is much appreciated