Friday, 30 May 2014

Project Euler : Problem #2 - C++ Solution

This time, the problem is:
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.
I'm using a do-while loop here. Here is the code:
#include <iostream>
using namespace std;

int main()
{
    int a = 0, b = 1;
    int c, answer = 0;
    do{
        c = a + b;
        a = b;
        b = c;
        if(b%2==0){answer = answer + b;}
    }while(b<=4000000);
    cout<<"Answer is "<<answer;
    return 0;
}

Thursday, 1 May 2014

Project Euler : Problem #1 - C++ Solution


I was recently wandering around the internet, and I found out this awesome website, with some great mathematical problems which has to be solved using any programming language. You can easily get into the website by searching for "Project Euler" on Google. It has a great set of problems, to sharpen your problem solving skills in any programming languages. Here I'm posting the solution to the first problem. I will try to continue to give more solutions to more problems.

The problem is :

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
First go ahead an try to solve it on your own, and then refer the solution.
The solution to the problem is given below:


#include<iostream>
#include "conio.h";
using namespace std;
int main()
{
    int i;
    int result = 0;
    for(i=0;i<1000;i++)
    {
          if( i%3==0 || i%5==0 )
          {
                result = result + i;
          }    
    }
    cout<<"The answer is "<<result;
    getch();
    return 0;
}

Here is the output:

 :)

You might also like