最高素数

时间:2015-03-24 00:11:00

标签: ruby loops primes

我试图找到给定整数的最高素数。我可以让代码的第一部分工作,但是我检查以查看因子是否为素数的部分不起作用。我没有收到任何错误,但我收到的输出(puts)是空白的,所以我认为输出的是nil。我的代码出了什么问题?

def highestprime num

  i = 1
  counter = 0
  count = -1
  factors = []
  primes = []

  while (i < num/2) #checks for all factors of number
    i += 1
    if (num%i == 0)
      factors.push(i) #adds all factors to the end factors array
    end
  end

  while (counter < factors.length) #goes through whole array
    counter += 1
    count += 1
    while (i < factors[count]) #tests for particular index in array
      i += 1
      if (factors[count]%i == 0 and i != factors[count]) #if factor is divisible by a number, it is not prime, so break
        break
      elsif (factors[count]%i != 0 and i != factors[count]) #if it is not divisibe, then keep iterating
        next
      elsif (i == factors[count]) #if the end has been reached, then add to primes array
        primes.push i
      end
    end
  end
  puts primes.pop #print the biggest(last) prime number
end

3 个答案:

答案 0 :(得分:2)

第一个循环将i的部分值推送到factors;完成该循环后,i至少与factors中的每个值一样大。嵌套的while循环是唯一可以推送到primes的地方,只有i小于factors中的某个值才会运行,我们刚刚建立的那个值永远不会发生。

答案 1 :(得分:0)

我看到你在循环之间重用迭代器变量i,但我看不到你将它重置回1的位置。

也许那个?

答案 2 :(得分:0)

您应该查看prime库。你可以用几行重写整个事情:

require 'prime'
def highestprime num
  Prime.reverse_each(num) { |p| return p }
end

puts highestprime(10)
相关问题