【问题标题】:Trying to solve for the largest prime factor without recursion - Ruby试图在没有递归的情况下求解最大的素数 - Ruby
【发布时间】: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


    【解决方案1】:

    我不会给你完整的答案,因为这会破坏欧拉计划的练习对象。

    但是,您在解决问题方面几乎走上了正确的道路。你不想看数组p 没有被清空,那应该是收集你的素数。不过,您确实想查看not_p,因为这是您的每个因素的除数数组。

    我希望这会有所帮助。如果我能提供更多帮助,请告诉我。

    【讨论】:

    • 我还需要更多帮助。在数组 [3, 9, 11, 33] 中,99 都可以被整除,如果一个元素不能被任何不超过元素值一半的数字整除(所以对于 9,2~4 的任何数字)我推将该元素放入array#p。如果它有除数,我将除数推入 not_p。由于 9 确实有除数,因此 array#not_p 不是空的,因此 9 不会被推入 array#p。这是我的代码背后的逻辑,但它不起作用。我的代码没有做我想要做的事情,到底是什么原因?
    • 没错,但您的问题在于,在您第一次检测到非质数后,您的 not_p 数组中有项目。因此,每次您再次循环循环时 not_p.length 都不会除非你做点什么,否则不要再为零了。
    • 知道了!感谢您的建议,我将我的解决方案添加到此线程。
    【解决方案2】:

    啊,好吧!感谢您的建议菲尔纳什!事实上,我知道这个问题,并试图用 Array.clear 清除数组,但没有奏效。相反,我只是将 not_p = [] 移到迭代 arr.each do |x| 下面它奏效了!这是有道理的,因为当 not_p 移动到下一个元素时,它会重置为 []。非常感谢您的帮助,并且没有先提供答案!这是我的最终可行解决方案 =D

    def prime(num)
        arr = []
        p = []
    
        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| 
            not_p = []
            for i in (2..(x / 2)) 
                if x % i == 0 
                    not_p << i 
                end 
            end
            if not_p.length == 0 
                p << x 
            end
        end
        return p[-1] 
     end
    
    puts prime(99) # => 29
    

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2016-09-01
      • 2010-10-15
      • 2013-03-08
      相关资源
      最近更新 更多