1

I have a very basic question about Ruby loops.

This program as written returns the ith prime number +1 (ie the example should return 17). I know I could simply return cand-1, but I was wondering what the "Ruby way" of checking if the answer has been found at the bottom of the while loop and only incrementing if it hasn't.

def ith_prime(i)
  pI = 0 # primes index
  divs = []
  cand = 2

  until pI == i do 
    if divs.find { |div| cand%div == 0 } == nil
        divs << cand
        pI += 1
    end
    cand += 1
  end
  cand
end

puts ith_prime(7)
> 18

1 Answer 1

5

I use loop instead of while or until most of the time. This way I can put the exit condition anywhere in the loop.

I would write it like that (if I understood the problem correctly):

def ith_prime(i)
  pI = 0 # primes index
  divs = []
  cand = 2

  loop do
    unless divs.find { |div| cand%div == 0 }
      divs << cand
      pI += 1
    end

    break if pI == i

    cand += 1
  end

  cand
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.