(Hacker Rank) Even Fibonacci numbers - Solution

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static long fibo(long num) {
        long next1 = 1;
        long next2 = 1;
        long sumEven = 0;
        for (int i = 2; i <= num; i++) {
            long next = next1 + next2;
            if (next%2 == 0 && next < num) {
                sumEven += next;
            }
            if (next > num) {
                return sumEven;
            }
            next1 = next2;
            next2 = next;
        }
       
        return sumEven;
    }
   
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
       
        int numTests = sc.nextInt();
        for (int i = 0; i < numTests; i++) {
            long n = sc.nextLong();
            long sum = fibo(n);
            System.out.println(sum);
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução