Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fixnum and prime numbers in ruby

Before I set about to writing this myself, has anyone seen a ruby implementation of the following behavior?

puts 7.nextprime();     #=>  11
puts 7.previousprime(); #=>  5
puts 7.isprime();       #=> true

Obviously this kind of thing would be ugly for large numbers but for integers never exceeding a few thousand (the common instance for me) a sensible implementation is doable, hence the question.

like image 830
dreftymac Avatar asked Dec 13 '22 04:12

dreftymac


1 Answers

Ruby comes with a built-in Prime class that allows you to iterate through primes starting at 1, but I see no way to initialize it with a starting value other than 1, nor a predicate check to determine whether or not a number is prime. I'd say go for it, though you should keep in mind that math in Ruby can be slow and if performance is a factor you may be better off considering writing it as a C or Java extension. Here's an example of how to use RubyInline to generate primes in C.

Also, I suggest you avoid using the method name 7.isprime - the convention in Ruby is 7.prime?.

like image 131
Brian Guthrie Avatar answered Dec 25 '22 22:12

Brian Guthrie