Problem #2

This is problem 2 from project Euler. The task is to find the sum of all the even numbers which make up the Fibonacci sequence that starts with 1 and is less than 4 million.

/*
 * challenge2.cpp
 * 
 * This is challenge 2 of project Euler. The objective is to find the sum of the even numbers that lie within
 * the fibonacci sequence calculated up to 4,000,000.
 * 
 * Copyright 2012 Bill Heaster <TheCreator@ApexLogic.net>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */


#include <iostream>

using namespace std;

int main(int argc, char **argv)
{
	
	//make array, fill with fibonici sequence
	
	int myArray [4000];
	
	int a =1;
	int b = 2;
	int c = 0;
	
	int cnt = 2;
	
	int temp, res;
	
	//add the beginning to the array
	myArray[0] = a;
	myArray[1] = b;
	
	
	
	while(c < 4000000)
	{
		c = a + b;
		temp = c;
		if(temp % 2 == 0) //if it is even
		{		
			myArray[cnt++] = c;
		}
		 a = b;
		 b = c;
	 }
	
	int i;	
	res = 0;
	for(i = 0; i<cnt; i++)
	{
		res+=myArray[i];
	}
	
	cout<<"the sum of the even numbers within the fibonacci sequence, up to 4 million is: "<<res<<endl;
	
	return 0;
}

Leave a Reply