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();
    }
}
Community
  • 1
  • 1
K Mass
  • 53
  • 2
  • 3
  • 9
  • 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(); } } – K Mass Oct 07 '12 at 19:03
  • You can edit your post to add the code.. – Rohit Jain Oct 07 '12 at 19:03

4 Answers4

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...

Usman Salihin
  • 291
  • 1
  • 8
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.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
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; 
    } 
}
alvonellos
  • 1,009
  • 1
  • 9
  • 27
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 + " ");
        }
}
exexzian
  • 7,782
  • 6
  • 41
  • 52