In: Computer Science
Fibonacci Sequence in JAVA
f(0) = 0, f(1) = 1, f(n) = f(n-1) + f(n-2)
Part of a code |
public class FS { public static void main(String[] args){ IntSequence seq = new FibonacciSequence(); for(int i=0; i<20; i++) { if(seq.hasNext() == false) break; System.out.print(seq.next()+" "); } System.out.println(" "); } } |
///Fill in the rest of the code! |
Output |
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 |
You should define IntSequence as the interface.
You can't use for, while loop.
Thanks!!
IntSequence.java
------
public interface IntSequence
{
public boolean hasNext();
public int next();
}
FibonacciSequence.java
====
public class FibonacciSequence implements IntSequence {
private int n;
public int next(){
int f = 0;
int f1 = 0, f2 = 1;
if(n == 0)
f = 0;
else if (n == 1)
f = 1;
else{
for(int i = 2; i
<= n; i++)
{
f = f1 + f2;
f1 = f2;
f2 = f;
}
}
n++;
return f;
}
@Override
public boolean hasNext() {
return true;
}
}
FS.java
----
public class FS {
public static void main(String[] args){
IntSequence seq = new
FibonacciSequence();
for(int i=0; i<20; i++) {
if(seq.hasNext()
== false) break;
System.out.print(seq.next()+" ");
}
System.out.println(" ");
}
}
output
---
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
4181