some image

Codes and Tags

Solucionando Problem 2 – Project Euler

Etiquetas: , Blog, Challenges No comments

Bien, luego de revisar el Problema 2 de Project Euler aqui planteo mi solucion :)

Problema

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.

Solucion

/**
 * 
 * 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.
 * 
 * @author codesandtags
 * 
 */

public class Problem2 {

	public static void main(String[] args) {
		
		Problem2 solve = new Problem2();
		System.out
				.println("Sum even-valued terms, whose values are below 4 millions : "
						+ solve.sumFibonacciEven(4000000));

	}

	/**
	 * Obtiene la suma de los numeros pares en la serie de fibonacci, cuyo valor
	 * no supere el limite enviado por parametro
	 * 
	 * @param limit
	 * @return
	 */
	public long sumFibonacciEven(long limit) {
		long sum = 0;
		long a = 1;
		long b = 0;
		while (a < limit) {
			// Se suman solo los numeros impares
			if ((a & 1) != 0) {
				//System.out.println("a " + a);
				sum += a;
			}
			//Aplicacion de la sucesion de fibonacci
			a = a + b;
			b = a - b;
		}
		return sum;
	}

}

About Edwin Torres

Related Posts

  • Logo Java
  • Logo Java
  • Logo Java
  • Project Euler Logo

Add your comment