Fixnum and primes in ruby

Before I started writing this myself, did anyone see 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 not exceeding several thousand (a common example for me), a reasonable implementation is feasible, hence the question.

+4
source share
2 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 start value other than 1, and not check the predicate to determine if the number is prime. I would say go for this, although you should keep in mind that math in Ruby can be slow, and if performance is a factor, you might be better off looking at it as an extension of C or Java. Here's an example of how to use RubyInline to generate prime numbers in C.

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

+10
source

Take a look at the snippets found here . They can give you a hat.

+3
source

All Articles