Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if a value is a prime number in Ruby? Both the easy and the hard way?

Tags:

algorithm

ruby

I am trying to create a program that will test whether a value is prime, but I don't know how. This is my code:

class DetermineIfPrime
def initialize (nth_value)
@nth_value = nth_value
primetest
end

def primetest
  if Prime.prime?(@nth_value)
   puts ("#{@nth_value} is prime")
  else
   puts ("This is not a prime number.")
  end
rescue Exception
puts ("#{$!.class}")
puts ("#{$!}")
 end
end

And every time I run that it returns this.

NameError
uninitialized constant DetermineIfPrime::Prime

I tried other ways to do the job, but I think this is the closest I can get.

I also tried this:

class DetermineIfPrime
def initialize (nth_value)
@nth_value = nth_value
primetest
end

 def primetest
 for test_value in [2, 3, 5, 7, 9, 11, 13] do
  if (@nth_value % test_value) == 0
   puts ("#{@nth_value} is not divisible by #{test_value}")
  else
   puts ("This is not a prime number since this is divisible by #{test_value}")
  break
  end
 end
 end
end

Or am I just doing something wrong?

like image 959
user1542383 Avatar asked Aug 01 '12 15:08

user1542383


People also ask

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

The easiest way to solve this problem is to use trial division. Go through each number n, and check the remainder of dividing n by every number before it besides 1. If you find a number that has a remainder of 0, you know n is not prime. So if n = 9, you say 9 % 2 == 0 #=> false , then 9 % 3 == 0 #=> true .

How do you easily check if a number is prime or not?

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


3 Answers

Ruby has built in method to check if number is prime or not.

require 'prime'

Prime.prime?(2)  #=> true
Prime.prime?(4)  #=> false
like image 108
r3b00t Avatar answered Oct 22 '22 17:10

r3b00t


def is_prime?(num)
  return false if num <= 1
  Math.sqrt(num).to_i.downto(2).each {|i| return false if num % i == 0}
  true
end

First, we check for 0 and 1, as they're not prime. Then we basically just check every number less than num to see if it divides. However, as explained here, for every factor greater than the square root of num, there's one that's less, so we only look between 2 and the square root.

Update

def is_prime?(num) return if num <= 1 (2..Math.sqrt(num)).none? { |i| (num % i).zero? } end

like image 15
AndreiMotinga Avatar answered Oct 22 '22 17:10

AndreiMotinga


The error you are getting is because you haven't required Primein your code, You need to do require Prime in your file.

One cool way I found here, to check whether a number is prime or not is following:

class Fixnum
  def prime?
    ('1' * self) !~ /^1?$|^(11+?)\1+$/
  end
end

10.prime?
like image 8
Saurabh Avatar answered Oct 22 '22 17:10

Saurabh