我有以下代码
#!/usr/bin/ruby -w
c = 1
d = Array.new(6965) #6965 is the amount of abundant numbers below 28123 of which all numbers greater than that can be written as the sum of two abundant numbers
f = 0
while c < 28124 # no need to go beyond 28123 for this problem
a = 0
b = 1
i = true # this will be set to false if a number can be written as the sum of two abundant numbers
while b <= c/2 + 1 # checks will go until they reach just over half of a number
if c % b == 0 # checks for integer divisors
a += b # sums integer divisors
end
b += 1 # iterates to check for new divisor
end
if a > c # checks to see if sum of divisors is greater than the original number
d << c # if true it is read into an array
end
d.each{|j| # iterates through array
d.each{|k| # iterates through iterations to check all possible sums for number
# false is declared if a match is found. does ruby have and exit statement i could use here?
i = false if c - j - k == 0
}
}
c+=1 # number that we are checking is increased by one
# if a number cannot be found as the sum of two abundant number it is summed into f
f += c if i == true
end
puts f
对于以下代码,每当我尝试对d
数组进行双重迭代时,都会出现以下错误:
euler23:21:in block (2 levels) in ' from euler23:20:in block in ' from euler23:19:in '
-': nil can't be coerced into Fixnum (TypeError)
from euler23:21:ineach'
from euler23:20:ineach'
from euler23:19:in
由于我对 Ruby 不熟悉,因此我为解决此问题所做的各种尝试都是徒劳的。我感觉有些库我需要包含,但我的研究没有提到任何库,我很茫然。这段代码旨在将所有不能写成两个丰富数字之和的数字相加;这是欧拉计划的第二十三道题。