Another way of looking at the same problem is how to group their exponents to absolutely minimize duplicate computations :
31*29*23*19*17*11*5*3*2*
(13*11*5*3*2*
(7*5*3*2*
(3*2*(2)^2)^2)^2)^2
8683317618811886495518194401280000000:
2^31 3^15 5^7 7^4 11^3 13^2 17 19 23 29 31
Notice still there are many copies of ((11)*5)*3*2
, but once you set them to temp variables along the way ….
31 * 29 * 23 * 19 * 17
* (x = 11 * (y = (z = 3 * 2) * 5))
* (13 * x * (7 * y * (z * (2)^2)^2)^2)^2
… instead of 32 multiplication ops at the worst case linear scenario, now we have just
4 mults (*
) on the primes above half way (so always a single copy),
4 mults in 2nd row to define the 3 temp variables,
6 more mults at 3rd row, and finally,
4 nested squarings
Leading to a total of just 18 mult-or-square ops in total. Once in a blue moon, when the exponents are so well lined up, like 10!
, one can even write it as
7 * (5 * (3 * (2) ^ 2) ^ 2) ^ 2
7 * 720^2 (the most succinct form I'm aware of)
Rule of thumb for prime factorization prior to factorials is realizing for most of the primes you need you don't even need to do any division at all - since the higher half cannot even have 2 copies of itself, and like 75% of the prime range would have a max of 3 copies.
So it's mostly just the tiny primes with lots of copies that you actually need to calculate precisely. e.g.
For factorials <= 120
, only 4 primes have reached at least its own square and require extra processing - 2, 3, 5, and 7
. Factorials <= 360
, add in 11, 13, and 17
120 ! is already kinda big - 199 digits in decimal
360 ! larger still, 766 digits
262,143 ! is something like 1.306 mn digits
And most of the time, it's not worth the hassle to pre-take-out trailing zeros.
ps : to someone else's point, the factorials from 3!
to 6!
all have a very common approach
3 ! = 6 = 2^3 - 2 = 1 + 2 + 3
4 ! = 24 = 3^3 - 3 = 5^2 - 1
5 ! = 120 = 5^3 - 5 = 11^2 - 1
6 ! = 720 = 9^3 - 9 = 27^2 - 9 = 3^6 - 9
No factorization even needed, since all 4 use the same value for the cubing and the subtraction.
4! + 5! = 144 = 12^2
5! + 6! = 840 = 29^2 - 1
2*2*2 * 3 * 5
is equal to120
, right? What confuses you about that? – Aristocracy