From: Ruby Student Date: 2008-11-28T00:11:58+09:00 Subject: Re: Ayuda con Ejercicio ------=_Part_36678_27717966.1227799011045 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On Sun, Nov 23, 2008 at 3:26 AM, Todd Benson wrote: > On Thu, Nov 20, 2008 at 11:21 AM, wrote: > > On Nov 19, 3:53 pm, Fernando Villafuerte > > wrote: > >> lo que no se como hacer... es que el > >> resultado consiste solamente en la suma de los resultados > >> pero solo los que son n=FAmeros pares... > > > > Solo te hace falta agregar una variable para la suma, incrementandola > > cuando el numero es par (al dividirlo en 2 el residuo es cero): > > > >> a =3D 1 > >> b =3D 2 > >> stop =3D 4_000_000 > > > > suma =3D 0 > > > >> (1...500).each do > >> s =3D a + b > >> a =3D b > >> b =3D s > > > > suma =3D suma + b if 0 =3D=3D b.modulo(2) > > > >> break if a > stop > >> end > > > > puts =3D suma > > For fun (no guarantee of accuracy, but works for 4_000_000)... > > include Math > R =3D Math.sqrt(5) #radical > P =3D (1 + R) / 2 #phi > my_number =3D 4_000_000 > #inverting my_number to see approximately where n sits for F(n) > max_inverted =3D (log((my_number - 0.5) * R) / log(P)).to_i > #adding up F(n) for 0 to n > even_sum =3D (0..max_inverted).inject do |s, i| > #next line is for direct F(n) > #the inversion above is the opposite of this > fib =3D (((P**i) - (1-P)**i) / R).floor > #see if it's even > fib % 2 =3D=3D 0 ? (s + fib) : s > end > p even_sum > > > ...It would be interesting to see what ceilings (like 4_000_000) this fai= ls > for. > > cheers, > Todd > > Fernando, El ejercicio del cual hablas es parte del web site: www.eulerorg.net, donde se ofrece un largo numero de otros ejercicios interesantes. La siguiente is mi solucion, aunque no la mejor, pero es otra manera. Que te diviertas! =3Dbegin 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. http://projecteuler.net =3Dend MAXSUM =3D 4000000 def fibo(previous_fibo, current_fibo,new_fibo,total) if new_fibo.remainder(2) =3D=3D 0 if new_fibo <=3D MAXSUM total =3D total + new_fibo else puts "Found it. It is: #{total}" exit end end new_fibo =3D previous_fibo + current_fibo previous_fibo =3D current_fibo current_fibo =3D new_fibo fibo(previous_fibo, new_fibo, new_fibo, total) end fibo(1,2,2,0) --=20 Ruby Student ------=_Part_36678_27717966.1227799011045--