Answer to Question #302711 in Java | JSP | JSF for kmr

Question #302711

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:

  • If the given number is a Fibonacci number, print the number
  • If the given number is NOT a Fibonacci number, print the sum of all odd Fibonacci numbers less than the given number.




1
Expert's answer
2022-02-25T17:39:18-0500
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);
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS