The Fibonacci sequence is constructed by adding the last two numbers of the sequence so far to get the next number in the sequence. The first and the second numbers of the sequence are defined as 0 and 1. We get:
0, 1, 1, 2, 3, 5, 8, 13, 21…
Write a function which takes input as a number:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
if (n == 0 || n == 1) {
System.out.println(n);
} else {
int answer = 2;
int first = 1;
int second = 1;
while (first + second <= n) {
if (first + second == n) {
answer = n;
break;
}
if ((first + second) % 2 != 0) {
answer += (first + second);
}
int tmp = second;
second += first;
first = tmp;
}
System.out.println(answer);
}
}
}
Comments
Leave a comment