2

Is there a way in R to obtain the prime factorization of a given number n that shows the prime factors along with their corresponding exponents?

For example, if the output was two vectors, the first would contain the prime factors of n and the second would contain the corresponding exponents.

just to give an example if n=123456

the first vector should be

2 3 643

the second one

6 1 1

as 123456 = 2^6x3^1x643^1 Thanks in advance for any help

piero

Joseph Wood
  • 7,077
  • 2
  • 30
  • 65
user730712
  • 106
  • 1
  • 6

2 Answers2

3

Using package numbers:

library(numbers)

fs = primeFactors(152)
# Prime factor vector:
unique(fs)
# Vector with exponents:
as.vector(table(fs))
topchef
  • 19,091
  • 9
  • 63
  • 102
3

I came across this in an answer provided by Richie Cotton for factoring numbers. With gmp and plyr we have:

> library(gmp)
> library(plyr)
> b <- count(asNumeric(factorize(123456)))
> b
    x freq
1   2    6
2   3    1
3 643    1

> b$x
[1]   2   3 643

> b$freq
[1] 6 1 1

The gmp package can handle much larger numbers than the numbers package. Another advantage of this setup is that all of the information is stored in one object (i.e. in b above there is no need to call further functions to obtain what you are looking for, simply subset b).

Community
  • 1
  • 1
Joseph Wood
  • 7,077
  • 2
  • 30
  • 65
  • 1
    Nice. Here's a way without ``plyr``: ``table(as.numeric(factorize(123456)))`` (which seems to work well enough) – PatrickT Jan 11 '20 at 09:35