3

What is the code to write in int Fibonacci (int n) without using "if" like they did here Java recursive Fibonacci sequence ? I tried to write this but it is wrong : Because in this program the list will be 1 1 2 3 5 8 and not 0 1 1 2 3 5 8

Here is the program I tried to write:

public class Fibonacci
{
    public static void main(String[] args)
    {
        int f = 0;
        int g = 1;

        for(int i = 1; i <= 10; i++)
        {
            f = f + g;
            g = f - g;
            System.out.print(f + " ");
        }

        System.out.println();
    }
}
2
  • Here is the program I tried to write : public class Fibonacci { public static void main(String[] args) { int f=0; int g=1; for (int i = 1; i <= 10; i++) { f = f + g; g = f - g; System.out.print(f+" "); } System.out.println(); } } Commented Oct 7, 2012 at 19:03
  • You can edit your post to add the code.. Commented Oct 7, 2012 at 19:03

4 Answers 4

11

Pure formula for calculating Fibonacci number:

public double getFibonacci(int n) {
    double f1 = Math.pow(((1 + Math.sqrt(5)) / 2.0), n);
    double f2 = Math.pow(((1 - Math.sqrt(5)) / 2.0), n);

    return Math.floor((f1 - f2) / Math.sqrt(5));
}

Hope this helps...

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for letting me know a mathematical formula for this
9

Your program is entirely correct; all you need to change is the location of the print statement:

public static void main(String[] args) {
  int f = 0;
  int g = 1;

  for(int i = 1; i <= 10; i++)
  {
    System.out.print(f + " ");
    f = f + g;
    g = f - g;
  } 

  System.out.println();
}

Alternatively, print g instead of f.

Comments

4

No if statements here:

public static void printFib(final int N) { 
    int f0 = 0; 
    int f1 = 1; 

    for (int i = 0; i < N; ++i) { 
        System.out.println(f0);   
        final int temp = f1; 
        f1 += f0; 
        f0 = temp; 
    } 
}

Comments

2

Here is the one that I follow, its quite short and does without using if

    public class ShortFibboCode{

    public static void main(String a[]) {
        int f = 0;
        int numUpto = 10; // number of series upto - change accordingly
        for(int t = 1; f < numUpto; t = f + (f = t))
            System.out.print((f + " ");
        }
}

4 Comments

t = f + (f = t) makes my head hurt.
@Code-Guru its simply reducing the two statement/step process into one
@sanix Yes, I get it...after a little bit of effort.
@Code-Guru there you go real Code-Guru

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.