Find sum of all Fibonacci number which are even and less than N.
Example 1:
Input : n=100 Output: 44 //2+8+34=44
Approach:
Java
public class EvenFibonacciNumbers {
public static void main(String[] args) {
long n = 100;
long ans = evenFebonacciSum(n);
System.out.println(ans);
}
private static long evenFebonacciSum(long n) {
long fib1 = 0;
long fib2 = 1;
long ans = 0;
// iterate till next fibo
// is less than n
while ((fib1 + fib2) < n) {
// if next fibo is even then add it
if ((fib1 + fib2) % 2 == 0)
ans += fib1 + fib2;
long temp = fib2;
fib2 = fib1 + fib2;
fib1 = temp;
}
return ans;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n=100;
int fib1=0;
int fib2=1;
int ans=0;
//iterate till next fibo
//is less than n
while((fib1+fib2)<n)
{
//if next fibo is even then add it
if((fib1+fib2)%2==0)
ans+=fib1+fib2;
int temp=fib2;
fib2=fib1+fib2;
fib1=temp;
}
cout<<ans<<"\n";
return 0;
}
No comments:
Post a Comment