ruby 中的fixnum 和素数
在我自己开始写这篇文章之前,有没有人见过以下行为的 Ruby 实现?
puts 7.nextprime(); #=> 11
puts 7.previousprime(); #=> 5
puts 7.isprime(); #=> true
显然,这种事情对于大数字来说是丑陋的,但对于永远不超过几千的整数(对我来说是常见的例子),合理的实现是可行的,因此是问题所在。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Ruby 附带了一个内置的 Prime 类,它允许您迭代从 1 开始的素数,但我看不出有什么方法可以用 1 以外的起始值来初始化它,也没有谓词检查来确定是否或者不是一个数字是素数。 我想说,尽管您应该记住,Ruby 中的数学运算可能会很慢,如果性能是一个因素,您最好考虑将其编写为 C 或 Java 扩展。 以下是如何使用 RubyInline 生成素数的示例在 C 中。
另外,我建议您避免使用方法名称
7.isprime
- Ruby 中的约定是7.prime?
。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 is7.prime?
.查看此处找到的片段。 他们可以给你一个良好的开端。
Take a look at the snippets found here. They could give you a headstart.