prime numbers with ruby
Contact me at LinkedIn  RailsZilla at Facebook  RailsZilla at twitter   google +1  Contact me at Xing  connect me at github

prime numbers with ruby

Posted by Marcello on 13. June 2012 in coffee break, Ruby

In the last two weeks I was reading a lot about prime numbers. As a child I started to love these special numbers. The Definition of a Prime number is, that it is a natural number greater than 1 that has no positive divisors other than 1 and itself.

There are different methods and ways to calculate a prime, in example Euclid’s proof or Euler’s analytical proof, but I don’t want to bore you too much with mathematical formulas.

Generally we can allways check if a number is a prime, using a ruby method. Just start your terminal/console and enter with IRB your Ruby environment:

1
2
13.prime?
=> true

You just have to concatenate this method after your number to find out if it is a prime or not. Now let’s do a first quick code for generating primes. In our quick example, we will iterate 100 times for getting 100 prime numbers. Start your terminal/console and enter with IRB your Ruby environment:

1
2
3
4
5
6
7
require 'prime'

p = Prime.new
(1..100).each do |n|
  q = p.next()
  puts "#{n}: #{q}"
end

That was easy…
But what shall we do, if we want only mersenne primes (a positive integer that is one less than a power of two) or just twin primes (a twin prime is a prime number that differs from another prime number by two, for example the twin prime pair 41, 43)?

So let’s start to write an own function to understand the principles of primes:

1
2
3
4
5
6
7
8
9
10
11
12
herewego = Numeric.new
(1..10000).each do
   |container|
   (2..(Math.sqrt(container).ceil)).each do |x|
      herewego = 1
      if (container.divmod(x)[1] == 0)
         herewego = 0
         break
      end
   end
   print "#{container}\," unless (herewego == 0)
end

What are we doing here?
A prime number cannot be the product of two integers. We test each number up to 10,000 to determine if it is a prime number. If our number is a prime, then there will be no smaller number that will divide into the number with a remainder of 0.
We just test each number which is smaller than our number, to see if it is possible to divide into the number with anything other, than a zero remainder.

If this is not the case, then our number is a prime.
Happy priming ;-)

Tags: , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter a secure code to see if you are a spammer ;-)

 

Copyright © 2011-2014  - RailsZilla – Ruby on Rails tutorials, tips and tricks All rights reserved. | Imprint | Privacy