Saturday, August 31, 2013

Euler question 2 sum of even fibonacci numbers

Learnt two points on this one, even though so simple. One of them has surely created a lot of errors!

When I first did this I declared the variable c but did not assign it a value before being used as part of a condition in a while loop (once in the loop was a + b). This was not spotted by the compiler but still compiled OK, then fell down and didn't work. The lesson seems to be always assign a value as soon as a variable is declared to avoid trouble spotting this type of problem later.

Second I had a warning in the syntax editor when comparing a signed and an unsigned integer. Did not cause a problem this time but easy to imagine it causing a problem in future

//============================================================================
// Name        : euler_q2_even_fibonacci.cpp
// Author      : mjl
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

int main() {

	//you can declare multiple variables of the same type on one line
	//separate by commas but ; at the end
	unsigned int a, b, c;
	a = 1;
	b = 1;

	// this did not work when I did not include the below
	//but still compiled OK!
	//Probably something to do with the use in a while statement
	//comparison before being assigned a value!
	c = 0;


	unsigned int upper_limit = 4000000;

	//use modulo to allow more for not just even numbers
	int modulo = 2;

	unsigned int answer = 0;

	//need a while loop, not a for loop
	while (c < upper_limit) {
		c = a + b;
		if (c % modulo == 0){
			answer += c;
		}
		a = b;
		b = c;
	}

	cout << "the answer is " << answer;
	return 0;
}

No comments:

Post a Comment