【发布时间】:2017-12-14 23:20:07
【问题描述】:
好的。我认为我有正确的想法找到 Euler #23 的解决方案(关于找到所有不能表示为两个丰富数之和的数字之和的方法)。
但是,很明显,我的一种方法太该死的野蛮了。 你如何解除暴力并使其发挥作用?
sum_of_two_abunds?(num, array) 是有问题的方法。我已经尝试预先排除某些数字,但它仍然需要很长时间,我什至不确定它是否给出了正确的答案。
def divsum(number)
divsum = 1
(2..Math.sqrt(number)).each {|i| divsum += i + number/i if number % i == 0}
divsum -= Math.sqrt(number) if Math.sqrt(number).integer?
divsum
end
def is_abundant?(num)
return true if divsum(num) > num
return false
end
def get_abundants(uptonum)
abundants = (12..uptonum).select {|int| is_abundant?(int)}
end
def sum_of_two_abunds?(num, array)
#abundant, and can be made from adding two abundant numbers.
array.each do |abun1|
array.each do |abun2|
current = abun1+abun2
break if current > num
return true if current == num
end
end
return false
end
def non_abundant_sum
ceiling = 28123
sum = (1..23).inject(:+) + (24..ceiling).select{|i| i < 945 && i % 2 != 0}.inject(:+)
numeri = (24..ceiling).to_a
numeri.delete_if {|i| i < 945 && i % 2 != 0}
numeri.delete_if {|i| i % 100 == 0}
abundants = get_abundants(ceiling)
numeri.each {|numerus| sum += numerus if sum_of_two_abunds?(numerus, abundants) == false}
return sum
end
start_time = Time.now
puts non_abundant_sum
#Not enough numbers getting excluded from the total.
duration = Time.now - start_time
puts "Took #{duration} s "
【问题讨论】:
-
如何编辑我的帖子以修复我的代码块?你的格式化工具很神秘。
-
我帮忙了。要输入代码块,只需将代码缩进 4 个空格(或使用编辑器中的
{}按钮为您输入)。还要记得缩进 Ruby 代码 2 个空格。 -
“我什至不确定它给出了正确的答案” --- 那你为什么不写一些测试用例呢?
-
您的优化尝试只会让这变得更加复杂。你最好摆脱它们。
-
另外,这与您的问题完全无关(祝您好运),但在
is_abundant?(num)方法中,您基本上是“如果条件为真则返回真,否则返回假”。对于这种类型的事情,你可以只返回条件本身的评估......