The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

Fibonacci Spiral Help?

I'm trying to write a Java program that will display the Fibonacci Spiral as shown here . For right now, I just have it printing the starting coordinates of the rectangle that's being drawn, along with its length. There's nothing wrong with my program, except for a little array problem that I can fix, but I think there is a fundamental flaw in my thinking for this program. Can someone take a look at my code below and see why it does not work?
*Note: This is a school project, so I don't want too much help telling me what I should do, I just need help telling me what I shouldn't have done and why.
Thanks!

Re: Fibonacci Spiral Help?

Inspect the way the code determines the location of a Fibonacci square (eg the uses of modulus). My understanding is that the squares are repetitive in fours, and so checking the remainder from dividing by 4 may be more appropriate. Also, I assume the getFibonacci method returns the value at position x in the series? Because that code isn't listed I'll just comment that this is in the loop of a drawing routine so it should be fast (precalculated)

Re: Fibonacci Spiral Help?

Calculating Fibonacci can be fast... O(n) with O(1) memory space

It might be easier to work with the corners rather than the centers because they are always aligned by at least one axis (either x or y), so there's no need to calculate offsets between different centers. Maybe stick to the top-left corner? Also, in your modulus section, you don't want to modulate with different numbers, but rather with 4 all the time and check to see what the remainder value is.

Re: Fibonacci Spiral Help?

In a loop, still O(n) time. True dat it's only a loop of 5, but it's still nice to be efficient

Sorry, I meant to calculate the series over and over again in a loop. For example (using your fib example function)

int n = 5;
for ( int i = 0; i < n; i++ ){
int fib = fib(i);
}

As the loop goes through, it recalculates the previously calculated fibonacci values, doing so in a drawing routine which may be called often. Of course, for 5 its not a big deal, but larger values the computation time starts to pile up

This is as opposed to previously computing the series up to n, then accessing these as needed