Read the question, write Java on the right, then Run or Check.
QuestionHint and solution stay closed until you open them
Read n (1-indexed). Print the n-th Fibonacci number (F1=1, F2=1).
Examples
Input
1
Output
1
Input
6
Output
8
Hint
- Keep two running values a,b.
Show correct code
Peek only after you have tried. You can still Check your own version.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long a = 1, b = 1;
for (int i = 3; i <= n; i++) { long c = a + b; a = b; b = c; }
System.out.println(n == 0 ? 0 : b);
}
}
Main.javaJava 21 · javac · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.