ruby 中的fixnum 和素数

发布于 2024-07-16 08:08:51 字数 246 浏览 3 评论 0原文

在我自己开始写这篇文章之前,有没有人见过以下行为的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

征﹌骨岁月お 2024-07-23 08:08:51

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 is 7.prime?.

你在我安 2024-07-23 08:08:51

查看此处找到的片段。 他们可以给你一个良好的开端。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文