Project Euler – Problem # 2 – Solved with Java & Python

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:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

One Possible Solution: Java

public class Problem2 {
	public static void main(String args[]){
		int sum = 0;
		int a = 0;
		int b = 1;
		int c = a + b;
		while (c < 4000000){
			if (c % 2 == 0){
				sum = sum + c;
			}
			a = b;
			b = c;
			c = a + b;
		}
		System.out.println(sum);
	}

}

One Possible Soulution: Python

# Python version = 2.7.2
# Platform = win32

def fib(n):
    """Determines the sum of the even numbers in the fibonacci sequence
    up to value n"""
    thesum = 0
    a, b = 0, 1
    while a < n:
        if a % 2 == 0:
            thesum = (thesum + (a))
        a, b = b, a + b
    return thesum

def main():
    """The main program - calls the fib function and prints the value
    returned from the function --> x"""
    x = fib(4000000)
    print x
    
if __name__ == '__main__':
    main()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s