Euler Prolem no. 2

I solved the second question from the euler’s problem set with python first then i tried to do the same with c++ and I realized that it just does the same thing and same logic to be applied just increasing number of lines to code in C++.

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

So I will start with how I first thought of writing a precise and simple code. As the last digit in the Fibonacci series is the sum of all the prior numbers so if we minus all the odd values from last digit that is 4 million, we will get sum of all even numbers. But i went with searching for all the even numbers one by one till 4 million and adding them.

Python Code ->

sum = 0               # Assign variable sum as 0
a, b = 0, 1                # Taking a and b as values in Fibonacci series
while b < 4000000:         # Last value should be 4 million
    if b % 2 == 0:         # Checking if even
        sum += b           # Adding up all even values
    a, b = b, a + b        # swapping first value with second
print(sum)                 # print the sum 

Output ->

 4613732   

C++ Code  ->

#include 
using namespace std;
int main()
{
	int sum = 0;
	
	//3 variables to create the Fibonacci sequence from 0 to 4000000
	int a = 0;
	int b = 1;
	int c = 0;
	
	while (b <= 4000000)
	{
		c = a + b;
		if (b % 2 == 0)      //check for even number
			total += b;
		a = b;
		b = c;
	}
 
	cout << sum <<endl;
	return 0;
}

Output ->

 4613732  

Practicing more Euler’s problem.

Advertisements

One thought on “Euler Prolem no. 2

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