Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- my_primeFactors <- function(num) {
- current <- num
- ret.vals <- vector()
- x <- 2
- while (x <= num - 1){
- while (current %% x == 0) {
- current <- current / x
- ret.vals <- c(ret.vals, x)
- }
- x <- x + 1
- }
- if (is.logical(ret.vals)) return(num) else return(ret.vals)
- }
- > my_primeFactors(12)
- [1] 2 2 3
- > primeFactors(n)
- [1] 2 2 3
- > as.numeric(factorize(12))
- [1] 2 2 3
- > # Rutina ad-hoc
- > system.time({my_primeFactors(n)})
- user system elapsed
- 9.980 0.000 10.031
- > # Paquete "numbers"
- > system.time({primeFactors(n)})
- user system elapsed
- 0.004 0.000 0.001
- > # Paquete "gmp"
- > system.time({as.numeric(factorize(n))})
- user system elapsed
- 0 0 0
- 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 %fn", n, currentPrime))
- n = n%/%currentPrime
- cat(sprintf("current prime :%fn", 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 %fn", n, currentPrime))
- #cat(sprintf("current prime before is: %fn", currentPrime))
- print(c("current prime before:", currentPrime))
- currentPrime = as.numeric(nextprime(currentPrime))
- #cat(sprintf("current prime after is: %fn", currentPrime))
- print(c("current prime after:", currentPrime))
- }
- }
- }
Add Comment
Please, Sign In to add comment