I have tried to print with for loop - here is the code look like
import java.util.*;
public class fibonacci{
public static void main(String args[]){
int n,i;
Scanner sc= new Scanner(System.in);
n=sc.nextInt();
sc.close();
int values[]=new int[n]; // space O(N) used
values[0]=0;
values[1]=1;
for(i=2;i<n;i++)values[i]=values[i-1]+values[i-2]; // single traversal O(N)
System.out.println("The nth fibonacci number is "+values[n-1]);
}
}
But I don’t know if is there any way to print without for loop.
For modern enterprise I would say Java has streams now so create an infinite stream and then foldleft on it and then something to take n number of values from the stream to print
I guess you can still make a decent living as a perl programmer where it’s needed. Not sure that one-liner would help you get a job somewhere else though.
Unfortunately, that was not mine … I don’t know perl innards well enough to come up with that, but perl surely lends itself to the opposite of Java’s practices of creating factories and interfaces for everything
IIRC, you would automatically generate classes that each inherit some value from their respective superclass. The last generated class would then contain the fibonacci number from position x, when they all have a print statement in them, the sequence comes automatically.
Since I didn’t see a real Java solution yet without a for loop, I decided I’d go for it here:
public class Main {
public static void main(String[] args) {
int limit = 10;
printFibonacci(limit);
}
private static void printFibonacci(int limit) {
Stream.iterate(Map.entry(0, 1), entry -> Map.entry(entry.getValue(), entry.getKey() + entry.getValue()))
.limit(limit)
.map(Map.Entry::getKey)
.forEach(System.out::println);
}
}
This works because Stream.iterate produces an infinite stream of values, starting with the initial pair of (0, 1) and repeatedly applying that lambda on the previous value. The stream then limits the number of iterations and maps to the first value only in order to print it out. This program produces the following value for the limit of 10: