计算 'R' 中的质因数

calculating prime factors in '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))
        }
    }
}

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

currentPrime = nextprime(currentPrime)

currentPrime = as.numeric(nextprime(currentPrime))