Skip to content

Instantly share code, notes, and snippets.

@iboB
Created April 15, 2013 14:49
Show Gist options
  • Save iboB/5388658 to your computer and use it in GitHub Desktop.
Save iboB/5388658 to your computer and use it in GitHub Desktop.
product sum solve
class Timer
def initialize
ObjectSpace.define_finalizer(self,
self.method(:finalize).to_proc)
@start = Time.new
end
def finalize(id)
p "Time: #{Time.now.to_f - @start.to_f} seconds"
end
end
timer = Timer.new
# program start
class Integer
def prime?
return true if self == 2
2.upto(self/2) do |i|
return false if self % i == 0
end
true
end
end
Lim = 100
q = (2..Lim).to_a
class Num
def initialize(n, a, b)
@n = n
@a = a
@b = b
end
attr :n, :a, :b
def to_s
"[#{@a}, #{@b}]"
end
end
peshos = []
sashos = []
q.each do |a|
a.upto(Lim) do |b|
peshos << Num.new(a*b, a, b)
sashos << Num.new(a+b, a, b)
end
end
#P: I can't find them
peshos.reject! do |p|
p.a.prime? && p.b.prime?
end
#S: I knew it
sashos.reject! do |s|
s.n%2 == 0 || (s.n-2).prime?
end
#P: Now i know
peshos.select! do |p|
sashos.detect { |s| p.a == s.a && p.b == s.b }
end
hp = Hash.new
peshos.each do |p|
hp[p.n] = hp[p.n] ? 2 : 1
end
peshos.reject! do |p|
hp[p.n] != 1
end
p peshos.length
#S: now I know, too
sashos.select! do |s|
peshos.detect { |p| p.a == s.a && p.b == s.b }
end
hs = Hash.new
sashos.each do |s|
hs[s.n] = hs[s.n] ? 2 : 1
end
sashos.reject! do |s|
hs[s.n] != 1
end
p peshos.length
p sashos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment