在' R'中计算素数因子

时间:2015-12-02 12:53:01

标签: r factors

我对R' R'我正在尝试开始学习它。我编写了以下程序来生成给定数字的素因子。但出于神秘的原因,它在一天结束时会产生一个无意义的列表。我无法找到这种情况发生的地点或原因。请帮忙。

library(gmp)
getPrimeFactors = function(n){
    primeList=c()
    if(isprime(n)){
        primeList <- append(primeList, n)
        return (primeList)
    }
    currentPrime <- 2
    while(TRUE){
        # Check if input is divisible by the current primeList
        if(n %% currentPrime == 0){
            cat(sprintf("the number %f is divisible by %f\n", n, currentPrime))
            n = n%/%currentPrime
            cat(sprintf("current prime :%f\n", currentPrime))
            primeList = append(primeList,currentPrime)
            currentPrime = 2
            if(isprime(n)){
                primeList <- append(primeList, n)
                return (primeList)
            }
        }
        else{
            #cat(sprintf("the number %f is NOT divisible by %f\n", n, currentPrime))
            #cat(sprintf("current prime before is: %f\n", currentPrime))
            print(c("current prime before:", currentPrime))
            currentPrime = nextprime(currentPrime)
            #cat(sprintf("current prime after is: %f\n", currentPrime))
            print(c("current prime after:", currentPrime))
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是nextprime(currentPrime)不返回基本R数值。它返回类bigz的值。查看cat(nextprime(2)的输出。 要修复代码,请更改

currentPrime = nextprime(currentPrime)

currentPrime = as.numeric(nextprime(currentPrime))