0

我正在做一个 CodeEval 问题,要求找出一个数字有多少种方式可以变成一个平方。这是问题的链接:

https://www.codeeval.com/open_challenges/33

当我从命令行运行程序时,它会非常快速地输出正确的解决方案,但是,当我将程序提交给 CodeEval 时,我不断收到错误消息:

“致命:分配内存失败”。

我是编程新手,不知道为什么会这样,有人可以向我解释一下。

这是我的代码:

def double_square(x)
#Create array for storing double squares
arr = []
#Make x an integer
x = x.to_i
#Solve for case 0
if x == 0 then arr << 0 end
sqrt_x = Math.sqrt(x)
sqrt_x_as_int = Math.sqrt(x).to_i
#Check if x is a perfect square, if it is add it to array with '0'
if sqrt_x/sqrt_x_as_int == 1.0
    arr << [0,x]
end
#Find squares of all numbers less than the square root of x
squares = (1..sqrt_x_as_int).map {|num| num**2}
#Create array containing the combinations of squares & if array contains x, delete it
combos = squares.combination(2).to_a.delete_if {|combo| combo.any? {|num| num == x}}
#Find the sum of each array and select the arrays whose sums are equal to x
sums = combos.map do |combo|
    sum = combo.inject(:+)
    if sum == x
        arr << combo
    end
end
#Return the amount of double squares for n
puts arr.count
end

lines = File.readlines(ARGV[0]).map {|line| line.strip}
lines[0].to_i.times {|i| double_square(lines[i+1])}
4

1 回答 1

0

我猜这是 CodeEval 的服务器或沙盒环境的问题。

于 2013-07-19T01:12:53.267 回答