我试图在Ruby中编写一个程序,找到给定数字的素因子,而不使用Ruby的.Prime类。我写的代码对我来说似乎是合乎逻辑的(如果是回旋),但由于某种原因,最后一行代码似乎没有用,我不明白为什么。代码仍然只返回给定数字的所有因子,而不是主要因素。
def prime(n)
array = []
r = Range.new(2, n - 1)
r.each { |x| array << x if n % x == 0 }
array.each { |x| puts x if (2..x - 1).each { |p| x % p != 0 }}
end
答案 0 :(得分:1)
您想检查(2..x - 1)
中的.all?
号码,而不是.each
:
def prime(n)
array = []
r = Range.new(2, n - 1)
r.each { |x| array << x if n % x == 0 }
array.each { |x| puts x if (2..x - 1).all? { |p| x % p != 0 }}
end
顺便说一句,我还建议为变量赋予有意义的名称,因为现在读取代码真的很难,这个实现更加清晰:
def prime?(num)
return false if num < 2
(2..Math.sqrt(num).to_i).each do |i|
return false if num % i == 0
end
true
end
def prime_factors(num)
(2..num - 1).inject([]) do |factors, i|
(num % i == 0) ? factors << i : factors
end.select { |factor| prime?(factor) }
end
p prime_factors(44)
答案 1 :(得分:1)
def prime_factors(n)
# It's clear what factors will hold.
# It helps you when you or someone else read it out
# after a while.
factors = []
# Keep the r. No problem.
r = Range.new(2, n-1)
# Array#select is nice for this task.
# select is good in case where you need to filter out certain
# values out of a list. It nicely separates the selection task.
factors = r.select { |x| n % x == 0 }
# It's better not to go for double block on a single line.
# It will become more readable this way.
# Also it's better to handle how the result is displayed outside
# the function and just to return the computed values.
factors.select do |x|
(2..x - 1).all? { |p| x % p != 0 }
end
end
答案 2 :(得分:0)
将此单个函数拆分为三个factors n
,prime n
和prime_factors n
然后将它们组合在一起似乎更合乎逻辑。这种设计更加模块化,更适合测试各个零件。例如如果所有逻辑都是全局的,你怎么能肯定地说你的程序正确地找到了素数?
def factors n
(2..(n/2).floor).select {|x| n % x == 0 }
end
def prime? n
return false unless n >= 2
(2..Math.sqrt(n).floor).all? {|x| n % x != 0 }
end
def prime_factors n
factors(n).select {|x| prime? x }
end