Ruby - 确定一个数字是否是素数 [英] Ruby - determine if a number is a prime

查看:50
本文介绍了Ruby - 确定一个数字是否是素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决 Project Euler 上的问题,以自学 Ruby 编程.我知道有一个内置函数可以做到这一点,但我避免使用内置函数来帮助我学习.

I'm running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I'm avoiding the built-in functions to help me learn.

所以我必须写一个方法来判断一个数是否是素数.第一种方法有效,但第二种方法无效.谁能解释一下原因?

So I have to write a method to determine if a number is a prime. The first method works, but the second doesn't. Can anyone explain why?

 def is_prime n
  for d in 2..(n - 1)
   if (n % d) == 0
    return false
   end
  end

  true
 end

 def is_prime2 n
  foundDivider = false
   for d in 2..(n - 1)
    foundDivider = ((n % d) == 0) or foundDivider
   end
  not foundDivider
 end

推荐答案

这是因为 = 的优先级高于 or.请参阅下面的 Ruby 的运算符优先级表(从高到低的优先级):

It's because = is of higher precedence than or. See Ruby's operator precedence table below (highest to lowest precedence):

[ ] [ ]=
**
! ~ + -
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
? :
= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
defined?
not
or and
if unless while until
begin/end

有问题的行被解析为...

The problematic line is being parsed as...

(foundDivider = ((n % d) == 0)) or foundDivider

...这当然不是你的意思.有两种可能的解决方案:

...which is certainly not what you mean. There are two possible solutions:

强制优先考虑你真正的意思......

Force the precedence to be what you really mean...

foundDivider = (((n % d) == 0) or foundDivider)

...或者使用 || 运算符代替,它比 = 具有更高的优先级:

...or use the || operator instead, which has higher precedence than =:

foundDivider = ((n % d) == 0) || foundDivider

这篇关于Ruby - 确定一个数字是否是素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆