0

/*I was able to output this: 0, 1, 1, X2, 3, 5, 8, X13, 21, 34, 55, X89, 144, 233, 377, X610, 987, 1597, 2584, X4181, 6765, however, I can seem to make it skip the numbers and replaces them with Q. I am stuck on this one. :(

import java.util.ArrayList;
import java.util.List;

public class FibonacciSequence {

    public static void main(String[] args) {
        long f = 0;
        List<Integer> testList = new ArrayList<Integer>();
        boolean executed;
        for(int i = 1; i<=21; i++) {

            f = fib(i);
            String space = ", ";
            if(i%4==0) {
                String x = "X";
                System.out.print(x);                
            }
            System.out.print(fib(i) + ", ");
        }
    }
    private static long fib(int i) { 
        if (i == 1) {
            return 0;
        }
        if (i <= 2) {
            return 1;
        }
        else {
            return fib(i-1)+fib(i-2);
        }
    }   
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
zvaniel
  • 25
  • 6
  • Hint: `if` also supports `else` – Michael Butscher Nov 16 '18 at 02:58
  • I don't really want to solve a programming exercise for you, but I will point out that you are calculating every fibonacci number from scratch each time through the loop, in a way where the cost of calculating the number approximately doubles for each step. You'd be much better off just using variables to remember the prior two numbers. – slevin Nov 16 '18 at 03:02
  • The recursive definition of Fibonacci is **very** expensive in Java. You need to use the loop instead. – Peter Lawrey Nov 16 '18 at 07:58

1 Answers1

0

Assuming I understand your question, use an else in addition to your if. I cleaned up your main method removing the variables you weren't using. I would simply prepend , after checking we aren't on the first element. Like,

public static void main(String[] args) {
    for (int i = 1; i <= 21; i++) {
        if (i != 1) {
            System.out.print(", ");
        }
        if (i % 4 == 0) {
            System.out.print("X");
        } else {
            System.out.print(fib(i));
        }
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249