would be all the integers in the range 2 to 10, including 10.
would be all the integers in the range 2 to 10, excluding 10.
Thanks, so if I say,
def prime? (num)
if num <= 1
elsif num == 2
else (2..num/2).none? do |i|
num % i == 0
what does num & i stands for here?
num is the formal parameter of the method, as it appears.
Inside the method,
num will be
Could you please post a link to this lesson so we can follow up?
Thanks a lot!
What will i be in that case?
Sorry, I was just trying to find a way to detect prime number and came across this method online.
But I really appreciate your help!
Sorry, forgot to cover that variable.
i is known as a block parameter and functions like a local variable of a method.
i will be the iterator, starting at
2 and progressing up to
num / 2. In the above example, (19), the range will be,
2, 3, 4, 5, 6, 7, 8, 9
No need to be sorry,
**So, basically function will try to divide given no by all the all the elements in range to find the prime no, **
**if It can't divide, it's a prime so, it gives true. **
and if it can divide, It's not a prime. So, it gives false, correct?
It won't find the prime as much as determine primeness if there are no factors found.
19 % 2 ... 19 % 9
None of these trials will net
0. So the loop will finish and 19 will fall out the bottom.
Not necessary. The loop will not run when num is 2.
Inside the loop,
def prime?(num) if num < 2 return false (2..num/2).none? do |i| if num % i == 0 return false end end return true end
I'm winging here, until I see the lesson. Please post the URL to the exercise. Thanks.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.