[R] Problems trying to generate a prime factor vector
Kevin Wright
wrightkevin3000 at gmail.com
Thu Dec 3 12:42:26 CET 2015
Hi,
I am very new to 'R' and am trying to write an R function which returns the
prime factors of a given number(n)
Unfortunately, the function only works for very small numbers, if for
example I pass 18 to the function
a mysteriously long vector is returned. I have not been able to find where
or why this is happening.
I know I've done something wrong. I've tried using debugging statements.
Sometimes the
currentPrime variable seems to become some sort of array?!
can you help?
library(gmp)
#passing 18 returns: 2 1 0 0 0 1 0 0 0 1 0 0 0 3 0 0 0 1 0 0 0 1 0 0 0 1 0
0 0 3 0 0 0
# expected: 2 3 3
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 prime
if(n %% currentPrime == 0){
cat(sprintf("the number %f is divisible by %f\n", n,
currentPrime))
n = n%/%currentPrime
cat(sprintf("value of n is %f\n", n))
cat(sprintf("current prime :%f\n", currentPrime))
primeList = append(primeList,currentPrime)
# print(c("list contents:", primeList))
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))
}
}
}
}
[[alternative HTML version deleted]]
More information about the R-help
mailing list