Click to See Complete Forum and Search --> : help with Fibonacci sequance


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

dlorde
April 22nd, 2009, 03:02 PM
Well, there are two main aspects of a piece of code you need to get right - the algorithm (logic) and the syntax.

You can tell if you've got the syntax right by compiling it - if the syntax is wrong, the compiler will complain.

The place to start is with the algorithm because this really determines what the code is going to do and therefore what code you're going to write - you can fix the syntax once you know what code you're going to write. You find out what the algorithm should be by reading the requirements and working out what they mean and how they will work.

Lucky for you, the requirements actually give you the class and method name and the algorithm, complete with an explanation of how to use it - it translates almost directly into Java.

So lets look at your code. Have you followed the requirements? The class name - Yes. The method name - No. The algorithm - No.

So even if you got the code to compile and run, you'd fail because you haven't followed the instructions, and you won't get the right results.

What about the Java syntax? You've declared a static method 'fib' that takes an int parameter, which is ok, but then you declare another method 'getNumber' inside it, which is not allowed. A method can't contain another method declaration. Other than that, the Java syntax is correct, but as I already said, the algorithm isn't, so it won't work properly.

The most important single aspect of software development is to be clear about what you are trying to build...
B. Stroustrup