【发布时间】:2015-03-10 23:41:53
【问题描述】:
我遇到了一个名为 Project Euler 的网站,一切都很顺利,直到我遇到第三个问题 - 最大素因数。我不想使用递归来解决它。我在网上看到了他们使用 Math.sqrt 的解决方案,我也不想使用它。固执,我知道。
我想只用循环和 if 语句来解决它。我假设输入是奇数。这是我的代码。如果 num = 99,输出一直显示为 [3],我不知道为什么。我尝试在任何地方放置一个 puts 语句,以查看每一步输出的内容。我意识到的一个问题是 array#p 在每次循环后都没有重置。我试过 array.clear 但这并没有太大帮助。有人能指出我正确的方向吗?是否有一些关于数组、循环和 if 语句的基本方面我没有得到?
def prime(num)
arr = []
p = []
not_p = []
# first I find all the numbers that num is divisible by
for i in (2..num/2)
if num % i == 0
arr << i
end
end # this should output [3, 9, 11, 33]
arr.each do |x| # I loop through each element in the above array
for i in (2..(x/2)) # I divide each element - x - by 2 because it cannot be divisble by anything greater than its half
if x % i == 0 # if x is divisble by i
not_p << i # I push the i into array#not_p
end # keep looping until i reaches x/2
end
if not_p.length == 0 # if there are no values in array#not_p, then I know x is a prime factor
p << x # so I push x into array#p
end
end
return p[-1] # returns the last element of the array, which is the largest
end
puts prime(99)
【问题讨论】:
标签: ruby loops if-statement