Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Fibonacci Sequence in Java

Tags:

java

python

I really suck at math. I mean, I REALLY suck at math. I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:

a = 0
b = 1
while b < 10:
    print b
    a, b = b, b+a

The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:

    public class FibonacciAlgorithm {

    private Integer a = 0;

    private Integer b = 1;

    public FibonacciAlgorithm() {

    }

    public Integer increment() {
        a = b;
        b = a + b;
        return value;
    }

    public Integer getValue() {
        return b;
    }
}

All that I end up with is doubling, which I could do with multiplication :( Can anyone help me out? Math pwns me.

like image 218
Naftuli Kay Avatar asked Jun 25 '09 17:06

Naftuli Kay


1 Answers

I'd do it this way:

public class FibonacciAlgorithm {

    private int a = 0;

    private int b = 1;

    public FibonacciAlgorithm() {

    }

    public int increment() {
        int temp = b;
        b = a + b;
        a = temp;
        return value;
    }

    public int getValue() {
        return b;
    }
}

This keeps it as close to your original Java code as possible.

[Editor's note: Integers have been replaced with ints. There is no reason to use Integers for this.]

like image 81
faceless1_14 Avatar answered Sep 26 '22 11:09

faceless1_14