编写一个函数,打印出每个数字1到100的所有因子。
真的是业余编码员,但到目前为止这是我的尝试。
def factors_numbers(n1,n2)
(n1..n2).each do |n|
factors = []
factors << 1 ##every number has a factor of 1
factors << n ##every number is a factor of itself
i = 1
while i < n
new_number = n % (n-i)
if new_number == 0 #if 0, divisible and that means two numbers are factors
factors << new_number
factors << (n-i)
end
i += 1
end
return factors
end
end
答案 0 :(得分:1)
以下是代码的改进版本:
def factors_numbers(n1,n2)
all_factors = {}
(n1..n2).each do |n|
factors = []
(1..Math.sqrt(n).floor).each do |i|
remainder = n % i
if remainder == 0 #if 0, divisible and that means two numbers are factors
factors << i
factors << n/i
end
end
factors = factors.sort.uniq
puts "Factors of #{n}: #{factors.join(',')}"
all_factors[n]=[factors]
end
return all_factors
end
答案 1 :(得分:0)
你想要独特的因素吗?也就是说,在1-100的范围内,我应该得到数字1一百次,还是仅一次?
最简单的方法是利用“注入”Enumerable方法。
def find_all_factors_between(n1,n2)
(n1..n2).inject([]) do |factors, num|
factors + (1..num).inject([]) { |arry, test| num % test == 0 ? arry + [test] : arry }
end
end
最后要注意的是Ruby有隐含的回报;也就是说,只要您方法的最后一行的输出是factors
变量,您就不必说return factors
。
答案 2 :(得分:0)
(n1..n2).each{|x| print "#{x}: #{(1..x).select{|y| x % y == 0}}\n"}
那应该做到这一点:)
编辑:实施Cary Swoveland的建议
答案 3 :(得分:0)
我的参赛作品将是:
def find_all_factors_between(n1, n2)
factors = -> (n) { (1..n).select {|i| n % i == 0} }
(n1..n2).each { |n| puts "Factors of #{n}: #{factors.(n).join(', ')}" }
end
find_all_factors_between(1,100)
答案 4 :(得分:0)
好吧,如果你想用枚举来做,那总是
def factor_numbers(rng)
factors = rng.map do |n|
(1..Math.sqrt(n).floor) # search numbers <= square root
.select { |d| n % d == 0 } # find factors <= square root
.flat_map { |x| [x, n / x] } # combine with factors >= square root
.sort # order from least to greatest
.uniq # remove dupes (basically the square root)
end
Hash[rng.zip(factors)] # rng = keys, factors = values
end
puts factor_numbers(1..100)
这不是最有效的,但我的观点是,您在C或JavaScript等语言中看到的许多for / while结构可以在Ruby中以其他方式表达。
答案 5 :(得分:0)
def factor_nums(n1,n2)
all_factors = {}
(n1..n2).each do |n|
factors = []
(1..n).each do |i|
remainder = n % i
factors << i if remainder == 0
end
all_factors[n] = factors
end
return all_factors
end