Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Created February 11, 2026 04:08
Show Gist options
  • Select an option

  • Save jmbarbone/43a8bb65b407e9b8e68e020ea21a8295 to your computer and use it in GitHub Desktop.

Select an option

Save jmbarbone/43a8bb65b407e9b8e68e020ea21a8295 to your computer and use it in GitHub Desktop.
prime factorization
primef <- function(x) {
x <- as.integer(x)
if (x <= 1) {
return(NaN)
}
res <- integer()
while (x %% 2L == 0L) {
res <- c(res, 2L)
x <- x %/% 2L
}
for (i in seq.int(3L, floor(sqrt(x)), by = 2L)) {
while (x %% i == 0L) {
res <- c(i, res)
x <- x %/% i
}
}
if (x > 2L) {
res <- c(x, res)
}
res
}
primef(123456)
primef(12171992)
primef(19921217)
primef(prod(17, 13, 11, 7, 5, 3, 2, 2, 2, 2))
primef <- function(x) {
  x <- as.integer(x)
  if (x <= 1) {
    return(NaN)
  }
  
  res <- integer()
  
  while (x %% 2L == 0L) {
    res <- c(res, 2L)
    x <- x %/% 2L
  }
  
  for (i in seq.int(3L, floor(sqrt(x)), by = 2L)) {
    while (x %% i == 0L) {
      res <- c(i, res)
      x <- x %/% i
    }
  }
  
  if (x > 2L) {
    res <- c(x, res)
  }
  
  res
}

primef(123456)
#> [1] 643   3   2   2   2   2   2   2
primef(12171992)
#> [1] 31051     7     7     2     2     2
primef(19921217)
#> [1] 19921217

primef(prod(17, 13, 11, 7, 5, 3, 2, 2, 2, 2))
#>  [1] 17 13 11  7  5  3  2  2  2  2

Created on 2026-02-10 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment