Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - determine if a number is a prime

Tags:

ruby

I'm running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I'm avoiding the built-in functions to help me learn.

So I have to write a method to determine if a number is a prime. The first method works, but the second doesn't. Can anyone explain why?

 def is_prime n
  for d in 2..(n - 1)
   if (n % d) == 0
    return false
   end
  end

  true
 end

 def is_prime2 n
  foundDivider = false
   for d in 2..(n - 1)
    foundDivider = ((n % d) == 0) or foundDivider
   end
  not foundDivider
 end
like image 607
Jaco Pretorius Avatar asked Aug 29 '10 10:08

Jaco Pretorius


People also ask

How do you check if a number is a prime number?

If a number has only two factors 1 and itself, then the number is prime.

Is prime function Ruby?

The prime? function in Ruby returns a boolean value. It returns true if the number is prime, else it returns false.

What is the fastest way to check if a number is prime?

The simplest primality test is trial division: given an input number, n, check whether it is evenly divisible by any prime number between 2 and √n (i.e. that the division leaves no remainder). If so, then n is composite. Otherwise, it is prime.


2 Answers

It's because = is of higher precedence than or. See Ruby's operator precedence table below (highest to lowest precedence):

[ ] [ ]=
**
! ~ + -
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
? :
= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
defined?
not
or and
if unless while until
begin/end

The problematic line is being parsed as...

(foundDivider = ((n % d) == 0)) or foundDivider

...which is certainly not what you mean. There are two possible solutions:

Force the precedence to be what you really mean...

foundDivider = (((n % d) == 0) or foundDivider)

...or use the || operator instead, which has higher precedence than =:

foundDivider = ((n % d) == 0) || foundDivider
like image 159
Chris Schmich Avatar answered Oct 14 '22 11:10

Chris Schmich


Ruby comes with predefined classes such as Prime. All you have to do is to require that class into your project.

require 'prime'

Than, you can use some of the Prime methods such as first to get first x prime elements:

Prime.first(5) # Ret => [2, 3, 5, 6, 11]

Or you could do something like this:

Prime.each(100) do |prime|
  p prime # Ret => [2, 3, 5, 7, 11, ..., 97]
end

I hope you find this useful.

like image 45
miksiii Avatar answered Oct 14 '22 10:10

miksiii