Guest User

Untitled

a guest
Feb 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. my_primeFactors <- function(num) {
  2.  
  3. current <- num
  4. ret.vals <- vector()
  5. x <- 2
  6. while (x <= num - 1){
  7. while (current %% x == 0) {
  8. current <- current / x
  9. ret.vals <- c(ret.vals, x)
  10. }
  11. x <- x + 1
  12. }
  13. if (is.logical(ret.vals)) return(num) else return(ret.vals)
  14. }
  15.  
  16. > my_primeFactors(12)
  17. [1] 2 2 3
  18.  
  19. > primeFactors(n)
  20. [1] 2 2 3
  21.  
  22. > as.numeric(factorize(12))
  23. [1] 2 2 3
  24.  
  25. > # Rutina ad-hoc
  26. > system.time({my_primeFactors(n)})
  27. user system elapsed
  28. 9.980 0.000 10.031
  29. > # Paquete "numbers"
  30. > system.time({primeFactors(n)})
  31. user system elapsed
  32. 0.004 0.000 0.001
  33. > # Paquete "gmp"
  34. > system.time({as.numeric(factorize(n))})
  35. user system elapsed
  36. 0 0 0
  37.  
  38. library(gmp)
  39. getPrimeFactors = function(n){
  40. primeList=c()
  41. if(isprime(n)){
  42. primeList <- append(primeList, n)
  43. return (primeList)
  44. }
  45. currentPrime <- 2
  46. while(TRUE){
  47. # Check if input is divisible by the current primeList
  48. if(n %% currentPrime == 0){
  49. cat(sprintf("the number %f is divisible by %fn", n, currentPrime))
  50. n = n%/%currentPrime
  51. cat(sprintf("current prime :%fn", currentPrime))
  52. primeList = append(primeList,currentPrime)
  53. currentPrime = 2
  54. if(isprime(n)){
  55. primeList <- append(primeList, n)
  56. return (primeList)
  57. }
  58. }
  59. else{
  60. #cat(sprintf("the number %f is NOT divisible by %fn", n, currentPrime))
  61. #cat(sprintf("current prime before is: %fn", currentPrime))
  62. print(c("current prime before:", currentPrime))
  63. currentPrime = as.numeric(nextprime(currentPrime))
  64. #cat(sprintf("current prime after is: %fn", currentPrime))
  65. print(c("current prime after:", currentPrime))
  66. }
  67. }
  68. }
Add Comment
Please, Sign In to add comment