P
Paolo Capriotti
My previous solution contained an error. This is a new version,
corrected and slightly optimized, but still not quite as fast as the
fastest solutions.
Paolo
--
class Integer
def divisors
res =3D []
i =3D 1
while i*i < self
if self % i =3D=3D 0
res << i
end
i +=3D 1
end
(res.size - 1).downto(1) do |k|
res << self / res[k]
end
res << i if i*i =3D=3D self
res
end
end
def weird(n)
possible_sums =3D Hash.new
possible_sums[0] =3D true
divisors =3D n.divisors
div_sum =3D divisors.inject(0) {|s, i| s+i }
return false if div_sum <=3D n
diff =3D div_sum - n
return false if divisors.include? diff
divisors.each do |i|
possible_sums.keys.sort.each do |s|
new_sum =3D s + i
case new_sum <=3D> diff
when -1
possible_sums[new_sum] =3D true
when 0
return false
when 1
break
end
end
end
return true
end
n =3D ARGV.shift or exit
n =3D n.to_i
m =3D ARGV.shift
m =3D m.to_i if m
range =3D m ? (n..m) : (1..n)
for i in range
puts i if weird(i)
end
corrected and slightly optimized, but still not quite as fast as the
fastest solutions.
Paolo
--
class Integer
def divisors
res =3D []
i =3D 1
while i*i < self
if self % i =3D=3D 0
res << i
end
i +=3D 1
end
(res.size - 1).downto(1) do |k|
res << self / res[k]
end
res << i if i*i =3D=3D self
res
end
end
def weird(n)
possible_sums =3D Hash.new
possible_sums[0] =3D true
divisors =3D n.divisors
div_sum =3D divisors.inject(0) {|s, i| s+i }
return false if div_sum <=3D n
diff =3D div_sum - n
return false if divisors.include? diff
divisors.each do |i|
possible_sums.keys.sort.each do |s|
new_sum =3D s + i
case new_sum <=3D> diff
when -1
possible_sums[new_sum] =3D true
when 0
return false
when 1
break
end
end
end
return true
end
n =3D ARGV.shift or exit
n =3D n.to_i
m =3D ARGV.shift
m =3D m.to_i if m
range =3D m ? (n..m) : (1..n)
for i in range
puts i if weird(i)
end