The Easiest Way to Save and Share Code Snippets on the web

Your snipt has been migrated to #newsnipt successfully.

euler problem 1 et 2 C solution

c

posted: Aug, 27th 2010 | jump to bottom

#include <stdio.h>
 
 
/*******************************************************************************************************************
 * Project Euler - Problem 1
 *
 * Problem 1 description:
 * 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.
 *
 *******************************************************************************************************************
 */
 
int findAnswerToProblem1( )
{
	int i;
	int sum = 0;
 
	for (i = 1; i < 1000; i++)
	{
		if ((i % 3 == 0) || (i % 5 == 0))
			sum += i;
	}
 
	return sum;
 
}
 
 
/*******************************************************************************************************************
 * Project Euler - Problem 2
 *
 * 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, ...
 * Find the sum of all the even-valued terms in the sequence which do not exceed four million.
 *
 *******************************************************************************************************************
 */
 
int findAnswerToProblem2() //4613732
{
	int op1 = 0, op2 = 1, result = 0, sum = 0;
	while (result <= 4000000)
	{
		result = op1 + op2;
		op1 = op2;
		op2 = result;
 
		if (result % 2 == 0) 
			sum = sum + result;
	}
 
	return sum;
}
 
 
 
int main( )
{
	printf("Answer to problem 1: %i \n", findAnswerToProblem1( ));
	printf("Answer to problema2: %i \n", findAnswerToProblem2( ));
	return 0;
}
 
17 views