如何在Ruby中测试值是否是质数?既简便又困难? [英] How can I test if a value is a prime number in Ruby? Both the easy and the hard way?

查看:97
本文介绍了如何在Ruby中测试值是否是质数?既简便又困难?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序来测试值是否为质数,但是我不知道该怎么做。这是我的代码:

I am trying to create a program that will test whether a value is prime, but I don't know how. This is my code:

class DetermineIfPrime
def initialize (nth_value)
@nth_value = nth_value
primetest
end

def primetest
  if Prime.prime?(@nth_value)
   puts ("#{@nth_value} is prime")
  else
   puts ("This is not a prime number.")
  end
rescue Exception
puts ("#{$!.class}")
puts ("#{$!}")
 end
end

NameError
uninitialized constant DetermineIfPrime::Prime

我尝试了其他方法来完成这项工作,但我认为这是我能得到的最接近的方法。

I tried other ways to do the job, but I think this is the closest I can get.

我也尝试过此操作:

class DetermineIfPrime
def initialize (nth_value)
@nth_value = nth_value
primetest
end

 def primetest
 for test_value in [2, 3, 5, 7, 9, 11, 13] do
  if (@nth_value % test_value) == 0
   puts ("#{@nth_value} is not divisible by #{test_value}")
  else
   puts ("This is not a prime number since this is divisible by #{test_value}")
  break
  end
 end
 end
end

或者我只是做错了什么

推荐答案

Ruby内置了一种检查数字是否为素数的方法。

Ruby has built in method to check if number is prime or not.

require 'prime'

Prime.prime?(2)  #=> true
Prime.prime?(4)  #=> false

这篇关于如何在Ruby中测试值是否是质数?既简便又困难?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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