R中的素数函数 [英] Prime number function in R

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

问题描述

我正在尝试创建一个函数来测试给定的整数是否为素数,我尝试使用以下方法:

I am trying to create a function to test if a given integer is a prime number, I tried using the following:

tpn <- function(prime.num){

    if(prime.num==2){
        print("PRIME")
    } else {

    if(prime.num%%(2:(prime.num-1))!=0){
        print("PRIME")

    } else { 
        print("NOT PRIME")

}}}

这不起作用,虽然我不明白为什么.我正在检查给定的数字是否可以除以这个数字的任何整数而没有余数.如果不能,则该数为质数.

This doesn't work, although I cant understand why. I am checking to see if the given number can be divided by any of the integers up to this number with no remainders. If it cant, then the number is prime.

我发现的另一个解决方案是:

Another solution I found was:

tpn <- function(pn){

    if(sum(pn/1:pn==pn%/%1:pn)==2)
            print("prime")

}

这有效.虽然,我无法理解 sum(pn/1:pn == pn%/%1:pn) == 2 实际测试的内容.

This works. Although, I cant get my head around what sum(pn/1:pn == pn%/%1:pn) == 2 is actually testing for.

推荐答案

一个数 a 可以被一个数 b 整除,如果除法的结果 a/b 等于整数除法 a %/% b 的结果.任何整数pn 都可以被至少两个数字整除:1pn.质数是那些只能被这两者整除的数.破解代码:

A number a is divisible by a number b if the result of the division a / b is equal to the result of the integer division a %/% b. Any integer pn can be divided by at least two numbers: 1 and pn. Prime numbers are those than can only be divided by those two. Breaking out the code:

  1. pn/1:pn 是除以 1, 2, ..., pn
  2. pn %/% 1:pn 是整数除以 1, 2, ..., 的结果pn
  3. sum(pn/1:pn == pn %/% 1:pn) 是其中多少个相等,即pn.如果这个数字是 2,你就有一个质数.
  1. pn / 1:pn are the results of the divisions by 1, 2, ..., pn
  2. pn %/% 1:pn are the results of the integer divisions by 1, 2, ..., pn
  3. sum(pn / 1:pn == pn %/% 1:pn) are how many of these are equal, i.e., the number of integer divisors of pn. If this number is 2, you have a prime.

你的代码有什么问题:if 需要测试某些东西是 TRUE 还是 FALSE,但你传递给它的是一个完整的向量.另外,你的逻辑是错误的.应该是:

What was wrong with your code: if needs to test if something is TRUE or FALSE but you were passing it a whole vector. Also, your logic was wrong. It should have been:

is.prime <- function(num) {
   if (num == 2) {
      TRUE
   } else if (any(num %% 2:(num-1) == 0)) {
      FALSE
   } else { 
      TRUE
   }
}

一旦你决定返回一个逻辑,你就可以让你的代码更短:

And once you've settled on returning a logical, you can make your code a lot shorter:

is.prime <- function(n) n == 2L || all(n %% 2L:max(2,floor(sqrt(n))) != 0)

(其中包含@Carl 关于不检查所有数字的评论.)

(which incorporates @Carl's comment about not checking all numbers.)

这篇关于R中的素数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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