Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:14
Show Gist options
  • Save dmnugent80/c2e72f21a9241c7781e9 to your computer and use it in GitHub Desktop.
Save dmnugent80/c2e72f21a9241c7781e9 to your computer and use it in GitHub Desktop.
Sum of Even Fibonacci Numbers
public class Main
{
public static void main(String[] args)
{
EvenFib myObject = new EvenFib();
int sum = myObject.getEvenFibSum(4000000);
System.out.print("sum: " + sum);
}
}
public class EvenFib
{
public int getEvenFibSum(int max){
int sum = 0;
int i = 1;
int curr = 0;
while (curr <= max){
curr = getFib(i);
if (curr % 2 == 0){
sum += curr;
}
i++;
}
return sum;
}
public int getFib(int n){
if (n == 0)
return 0;
if (n == 1)
return 1;
return (getFib(n-1) + getFib(n-2));
}
}
/*output
sum: 4613732
*/
//Alternate Iterative Approach:
public class FibEven
{
public static void main(String[] args)
{
int sum = 0;
int num = 1;
int prevNum = 0;
int tempNum = 0;
while(num <= 4000000)
{
if(num % 2 == 0)
sum += num;
tempNum = prevNum;
prevNum = num;
num += tempNum;
}
System.out.println(sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment