存在函数d(n),其被定义为n的适当除数之和(小于n的数字,其均匀地划分为n)。 例如,220的适当除数是1,2,4,5,10,11,20,22,44,55和110; 因此d(220)= 284. 284的适当除数是1,2,4,71和142; 所以d(284)= 220。
我想在Ruby中实现这个d(n)函数。 我的第一直觉是使用for循环遍历所有值到n并检查模数。 以下代码有效:
我可以使用这样的for循环来使用它:
def d(n) proper_divisors = [] for i in 1...n if (n % i == 0) proper_divisors.push(i) end end return proper_divisors.inject(:+) end但是从之前的回答中我了解到it's very rare to use a for loop in Ruby 。 这就是我尝试这个的原因:
def d(n) (1..n).inject(0) { |total| total+ n if (n % (1..n) == 0) } end因此,从1 to n的值开始, total等于0,并且如果n可以等于1 to n ,则将n加到total 。 部分if (n % (1..n) == 0)不起作用,因为Range can't be coerced into Fixnum (TypeError) 。
我怎样才能实现我对一个范围取一个数的模数,如果它等于零则返回true?
There is a function d(n) which is defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). E.g., the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
I want to implement this d(n) function in Ruby. My first instinct would be to use a for-loop to loop over all values up to n and check the modulus. The code below works:
I can get it to work with a for-loop like this:
def d(n) proper_divisors = [] for i in 1...n if (n % i == 0) proper_divisors.push(i) end end return proper_divisors.inject(:+) endBut from a previous answer I learned that it's very rare to use a for loop in Ruby. That's why I tried this:
def d(n) (1..n).inject(0) { |total| total+ n if (n % (1..n) == 0) } endSo from the values from 1 to n I start with total equal to 0 and add n to the total if n can be equally divided by a number from 1 to n. The part if (n % (1..n) == 0) does not work since Range can't be coerced into Fixnum (TypeError).
How can I accomplish that I take the modulus of one number against a range and return true if it is equal to zero?
最满意答案
(修复版toro2k的回答)
def d(n) (1..n/2).inject(0) { |total, m| (n % m).zero? ? total + m : total } end d(220) # => 284Block to inject接受两个参数:集合的累加器和当前元素。 该块应该返回累加器的新值。 在您的代码中,您忽略当前元素(这使您尝试将n除以范围)
(fixed version of toro2k's answer)
def d(n) (1..n/2).inject(0) { |total, m| (n % m).zero? ? total + m : total } end d(220) # => 284Block to inject accepts two parameters: the accumulator and current element of the collection. This block should return new value of the accumulator. In your code you ignore the current element (which makes you try dividing n by a range)
更多推荐
发布评论