Skip to content

Instantly share code, notes, and snippets.

@masui
Created May 15, 2012 02:22
Show Gist options
  • Save masui/2698593 to your computer and use it in GitHub Desktop.
Save masui/2698593 to your computer and use it in GitHub Desktop.
fibprime2
#!/usr/bin/ruby
#
# フィボナッチ数列を生成してブロックを渡す
#
class Fib
def self.calc
fib = [1,1]
loop do
yield fib[0]
fib.push fib.shift + fib[0]
end
end
end
if $0 == __FILE__
Fib.calc { |fib|
puts fib
}
end
#!/usr/bin/ruby
#
# 素数かつフィボナッチ数を生成
#
# 2, 3, 5, 13, 89, 233, 1597, 28657, 514229, 433494437, 2971215073, ...
#
require 'Monitor'
lock = Monitor.new
require 'fib2'
require 'prime2'
h = {}
fib_thread = Thread.new do
Fib.calc { |fib|
if h[fib] == 'p' then
puts fib
end
lock.synchronize do
h[fib] = 'f'
end
}
end
prime_thread = Thread.new do
Prime.calc { |prime|
if h[prime] == 'f' then
puts prime
end
lock.synchronize do
h[prime] = 'p'
end
}
end
fib_thread.join
prime_thread.join
#!/usr/bin/ruby
#
# 素数を生成してブロックを渡す
#
class Prime
def self.calc
primes = [2]
puts 2
cand = 3
loop do
lim = Math.sqrt(cand).floor
primes.each { |prime|
if prime > lim then
yield cand
primes << cand
break
end
if cand % prime == 0 then
break
end
}
cand += 1
end
end
end
if $0 == __FILE__
Prime.calc { |prime|
puts prime
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment