Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed N
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
public class Solution {
static void Main(String[] args)
{
int t = Convert.ToInt32(Console.ReadLine());
for(int a0 = 0; a0 < t; a0++)
{
long n = Convert.ToInt64(Console.ReadLine());
Console.WriteLine(Sum(n));
}
}
static long Sum(long n)
{
if (n <= 1) return 0;
long a=0,b=1,c=0;
long sum =0;
for (long i = 2; i < n; i++)
{
c= a+b;
if(c<=n)
{
if(c%2==0)
sum+=c;
}
else
break;
a=b;
b=c;
}
return sum;
}
}
Live Code on Paiza.io
Comments
Post a Comment