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:
By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.
Input Format
First line contains that denotes the number of test cases. This is followed by lines, each containing an integer, .
Output Format
Print the required answer for each test case.
Constraints
Sample Input
2
10
100
Sample Output
10
44
source code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t!=0)
{
BigInteger n=sc.nextBigInteger();
BigInteger f= BigInteger.valueOf(0);
BigInteger s= BigInteger.valueOf(1);
BigInteger sum= BigInteger.valueOf(0);
BigInteger ans= BigInteger.valueOf(0);
do{
if(sum.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(0)))
ans=ans.add(sum);
sum=f.add(s);
f=s;
s=sum;
}while(sum.compareTo(n)!=1);
System.out.println(ans);
t=t-1;
}
}
}
By considering the terms in the Fibonacci sequence whose values do not exceed N, find the sum of the even-valued terms.
Input Format
First line contains that denotes the number of test cases. This is followed by lines, each containing an integer, .
Output Format
Print the required answer for each test case.
Constraints
Sample Input
2
10
100
Sample Output
10
44
source code:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t!=0)
{
BigInteger n=sc.nextBigInteger();
BigInteger f= BigInteger.valueOf(0);
BigInteger s= BigInteger.valueOf(1);
BigInteger sum= BigInteger.valueOf(0);
BigInteger ans= BigInteger.valueOf(0);
do{
if(sum.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(0)))
ans=ans.add(sum);
sum=f.add(s);
f=s;
s=sum;
}while(sum.compareTo(n)!=1);
System.out.println(ans);
t=t-1;
}
}
}
No comments:
Post a Comment