红宝石中的fixnum和素数

时间:2022-09-03 11:23:41

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

在我开始自己编写之前,有没有人看过以下行为的ruby实现?

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.

显然,对于大数字来说,这种事情会很难看,但对于从不超过几千的整数(对我来说是常见的例子)来说,合理的实现是可行的,因此这个问题。

2 个解决方案

#1


10  

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.

Ruby附带了一个内置的Prime类,它允许你从1开始迭代素数,但我看不到用1以外的起始值初始化它,也没有用谓词检查确定数字是否为素数。我要说的是,尽管你应该记住,Ruby中的数学运算速度很慢,如果性能是一个因素,那么考虑将其编写为C或Java扩展可能会更好。这是一个如何使用RubyInline在C中生成素数的示例。

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

另外,我建议你避免使用方法名称7.isprime - Ruby中的约定是7.prime?。

#2


3  

Take a look at the snippets found here. They could give you a headstart.

看看这里发现的片段。他们可以给你一个开端。

#1


10  

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.

Ruby附带了一个内置的Prime类,它允许你从1开始迭代素数,但我看不到用1以外的起始值初始化它,也没有用谓词检查确定数字是否为素数。我要说的是,尽管你应该记住,Ruby中的数学运算速度很慢,如果性能是一个因素,那么考虑将其编写为C或Java扩展可能会更好。这是一个如何使用RubyInline在C中生成素数的示例。

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

另外,我建议你避免使用方法名称7.isprime - Ruby中的约定是7.prime?。

#2


3  

Take a look at the snippets found here. They could give you a headstart.

看看这里发现的片段。他们可以给你一个开端。