Fibonacci
Multiple implementations of Fibonacci algorithm, using extends
// for loops
class Fibonacci {
ArrayList<Integer> sequence;
int steps;
public Fibonacci() {
sequence = new ArrayList<Integer>();
sequence.add(0);
sequence.add(1);
this.getInput();
this.generateSequence();
}
public void getInput() {
Scanner input = new Scanner(System.in);
System.out.println("How many terms do you want to generate? (greater than 2)");
steps = input.nextInt();
System.out.println(steps);
}
public void generateSequence() {
for(int i = 2; i<steps; i++) {
sequence.add(sequence.get(i-2) + sequence.get(i-1));
}
System.out.println(sequence);
}
public static void main(String[] args) {
new Fibonacci();
}
}
Fibonacci.main(null);
// for loop with extends
class Fibo extends Fibonacci {
ArrayList<Integer> sequence;
int steps;
public Fibo() {
// inherits properties of for loop, so we don't have to rewrite functions
super();
}
public static void main(String[] args) {
System.out.println("\nUsing extends:");
new Fibo();
}
}
Fibo.main(null);
class Fibonacci {
ArrayList<Integer> sequence;
int steps;
public Fibonacci() {
sequence = new ArrayList<Integer>();
sequence.add(0);
sequence.add(1);
this.getInput();
this.generateSequence();
}
public void getInput() {
Scanner input = new Scanner(System.in);
System.out.println("How many terms do you want to generate? (greater than 2)");
steps = input.nextInt();
System.out.println(steps);
}
public void generateSequence() {
int i = 2;
while(i<steps) {
sequence.add(sequence.get(i-2) + sequence.get(i-1));
i++;
}
System.out.println(sequence);
}
public static void main(String[] args) {
new Fibonacci();
}
}
Fibonacci.main(null);
class Fibonacci {
ArrayList<Integer> sequence;
int steps;
public Fibonacci() {
sequence = new ArrayList<Integer>();
sequence.add(0);
sequence.add(1);
this.getInput();
this.generateSequence();
}
public void getInput() {
Scanner input = new Scanner(System.in);
System.out.println("How many terms do you want to generate? (greater than 2)");
steps = input.nextInt();
System.out.println(steps);
}
// recursive method to generate term i of fibonacci sequence
public int generateTerm(int i) {
if(i<=1) {
return i;
}
return generateTerm(i-2) + generateTerm(i-1);
}
// adds terms of fibonacci to sequence
public void generateSequence() {
for(int i = 2; i<steps; i++) {
sequence.add(this.generateTerm(i));
}
System.out.println(sequence);
}
public static void main(String[] args) {
new Fibonacci();
}
}
Fibonacci.main(null);