【发布时间】:2020-05-25 22:47:14
【问题描述】:
在从 m..n 的范围内,寻找除数平方和为完美平方的数字。返回数组中的数字和完美正方形。这是一个代码战挑战,只有由于超时而失败,测试本身就通过了。前任。 42 的除数是:1、2、3、6、7、14、21、42。这些除数的平方是:1、4、9、36、49、196、441、1764。平方除数的总和是 2500这是50 * 50,一个正方形。所以我会返回 [42, 2500]。
def list_squared(m, n)
divisors = []
matches = []
# array of divisors for each num in the range
(m..n).each do |num|
divisors.push((1..num).select { |n| num % n == 0 })
end
# sum the squares of each array and push last element of the set, and perfect square to matches array
divisors.each do |sets|
sum = 0
sets.each { |num| sum+=num**2 }
if Math.sqrt(sum)%1 == 0
matches.push([sets[-1],sum])
end
end
return matches
end
【问题讨论】:
-
另外Code Review 站点可能更适合此类问题。在那里你会(再次)找到Find all integers between m and n whose sum of squared divisors is itself a square。
-
您的问题标题非常笼统,因此以后很难找到此 Q/A。尝试使您的标题更具描述性。看看How do I ask a good question?。
-
是的,我可以使用下面的解决方案。感谢您的反馈。
标签: ruby algorithm optimization