Problem 26

Problem 26

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2	= 	0.5
1/3	= 	0.(3)
1/4	= 	0.25
1/5	= 	0.2
1/6	= 	0.1(6)
1/7	= 	0.(142857)
1/8	= 	0.125
1/9	= 	0.(1)
1/10	= 	0.1

Where 0.1(6) means 0.166666…, and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

Mam rozwiazanie:

[code]#!/usr/bin/env ruby
MAX = 1000
cycles = [0]+(1…MAX).collect do |d|
t = { }
exp = Math.log10(d).ceil
power = 10**exp
rem = 1

ciag reszt

rem = t[rem] = (rempower)%d while rem != 0 && !t[rem]
if rem != 0
rem0 = rem = t[rem]
n = 1
# ile roznych reszt dla ciagu
rem, n = t[rem], n+1 while t[rem] != rem0
# liczba cyfr w ciagu
n
exp
else
0
end
end
d = (1…MAX).max { |i, j| cycles[i] <=> cycles[j] }
puts “1/#{d} has a #{cycles[d]}-digit recurring cycle”[/code]

Dzięki za rozwiązanie, moje rozwiązanie było wolniejsze :(. Jednak zauważyłem, że używając powyższego kodu i uwzględniając tylko liczby pierwsze udaje się zejść z ~0.385s do ~0.180s(na mojej maszynie - 1.86 GHz Intel Core Duo).

Lol, mojego “mistrzowskiego” nic nie pobije :wink: Działa dłuuuuugo:

[code=ruby]require “mechanize”
require “prime”

agent = Mechanize.new
primes = Prime.new
pr = primes.next

results = []

while (pr <= 1000) do
pr = primes.next

agent.get(“http://wolframalpha.com”)
form = agent.page.forms.first
form.i = “1/#{pr}”
form.submit

v = agent.page.search("#i_0400_1").first.attributes[“alt”].value
if v =~ /period/
results << [pr, v.scan(/period \d+/).first.gsub("period ", “”).to_i]
end
end

puts a.max { |a, b| a[1] <=> b[1] }[/code]