我写这篇文章是为了找到数字num
的素数因子分解。它给出了正确的答案(例如,num
72的2,3,2,3,2),但它以奇数顺序出现。我无法弄清楚原因。我想知道是否有人看到了我不知道的事情。
$primes = [2]
$factors = []
num = 72
max = num
def isprime(n)
$primes.each do |x|
if n % x == 0 then
return
end
end
$primes.push(n)
return
end
i = 3
while i <= max
isprime(i)
i += 1
end
while !($primes.include?(num))
$primes.each do |x|
if num % x == 0 then
$factors.push(x)
num /= x
end
end
end
$factors.push(num)
puts $factors
答案 0 :(得分:1)
您需要在找到因素后立即中断$primes.each
循环,或者每次都完成循环。
while !($primes.include?(num))
$primes.each do |x|
if num % x == 0 then
$factors.push(x)
num /= x
break
end
end
end
$factors.push(num)
P.S:我只是留在算法方面而忽略了Ruby方面。
答案 1 :(得分:1)
你的内循环就像这样。考虑您正在测试号码72
您的素数数组将是[2,3,5,7...]
在第一次迭代的$primes.each do |x| loop
中,它会针对num = 72
测试2
并将其添加到factor
数组
Inner Iteration 1 => factors = [2], x = 2 , num = 36
Inner Iteration 2 => factors = [2,3], x = 3 , num = 12
Inner Iteration 3 => factors = [2,3], x = 5 , num = 12
Inner Iteration 3 => factors = [2,3], x = 7 , num = 12
Inner Iteration 3 => factors = [2,3], x = 11, num = 12
现在内部迭代存在,而素数循环又从2
开始。
Inner Iteration 1 => factors = [2,3,2], x = 2 , num = 6
Inner Iteration 2 => factors = [2,3,2,3], x = 3 , num = 2
内循环再次开始
Inner Iteration 1 => factors = [2,3,2,3,2], x = 2 , num = 2
你必须在内部循环中放置一个中断才能进行第一次因子分解并退出。
while !($primes.include?(num))
$primes.each do |x|
if num % x == 0 then
$factors.push(x)
num /= x
break
end
end