LoginSignup
1

More than 5 years have passed since last update.

R言語で素数判定

Last updated at Posted at 2016-01-27

素数判定

いろいろな場所で素数判定をおこなうコードはあるんだろうけど、自分の学習用にR言語で作成したものを載せます。

is.prime
is.prime <- function(num){
    # if num is integer
    if (num != as.integer(num)) return("Input is not integer!")
    # if num is less than 2
    if (num < 2){
     return("Input is wrong!")
    } 
    # if num is 2 or 3
    else if (num == 2 || num == 3) {
        return(TRUE)
    } else {

        for (i in 2:ceiling(num/2)){

            if ((num %% i) == 0) {

                return(FALSE)

            }

        }

     return(TRUE)
    }
}

この関数Primeは引数に2よりも大きい自然数をとります。

上記のis.prime関数を利用して、指定した範囲の素数をベクトルで戻す関数も作ってみました。

getPrime

getPrime <- function(max, min = 2){
    if (max != as.integer(max) || max < 2) return("Maximum value is wrong!")

    else if (min != as.integer(min)|| min < 2) return("Minimum value is wrong!")
    else {
    res <- NULL
    for (i in min:max){
        if(is.prime(i) == TRUE) res <- append(res,i)

    }
    return(res)
    }
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1