All integers \$n > 0\$ can be expressed in the form
$$n = \prod_{\text{prime } p} p^e = 2^{e_2} 3^{e_3} 5^{e_5} 7^{e_7} \cdots$$
This form is also known as it's prime factorisation or prime decomposition, and each integer has a unique prime factorisation.
As the bases are fixed, it is possible to reconstruct an integer when just given a list of the exponents of it's prime factorisation. For example, given \$E = [0,3,2,1,0,2]\$ we can reconstruct \$n\$ as
$$ \begin{align} n & = 2^0 3^3 5^2 7^1 11^0 13^2 \\ & = 1 \cdot 27 \cdot 25 \cdot 7 \cdot 1 \cdot 169 \\ & = 798525 \end{align} $$
Therefore, \$[0,3,2,1,0,2] \to 798525\$, and is the only such list (ignoring trailing zeros) that does so.
You are to take an input consisting of non-negative integers representing the exponents of the prime factorisation of some integer and output the integer with that prime factorisation.
Both the integer and the elements of the input will be within the bounds of your language, and you can take input in any convenient method. You may have an arbitrary (from 0 to infinite) number of trailing zeros in the input. The array will never be empty, but may be [0]
This is code-golf so the shortest code in bytes wins
Test cases
[0] -> 1
[1] -> 2
[3, 2] -> 72
[0, 1, 2] -> 75
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] -> 347
[6, 2] -> 576
[1, 7] -> 4374
[5, 7] -> 69984
[10, 5] -> 248832
[1, 0, 0, 8, 4] -> 168804902882
[3, 8, 10] -> 512578125000
[7, 9, 0, 8] -> 14523977994624
[4, 4, 7, 0, 0, 5, 5] -> 53377275216476250000
[1, 8, 1, 7, 8, 1] -> 150570936449966222190
[10, 0, 2, 8, 9] -> 347983339699826969600
[4, 8, 2, 3, 7, 9] -> 186021488852335961308083600
[7, 6, 6, 8, 6, 8, 4] -> 1014472920935186644572261278658000000
[9, 6, 7, 5, 1, 8, 10] -> 8865565384329431006794755470280000000
-
2\$\begingroup\$ Brownie points for beating my 6 byte Jelly answer which doesn't use the builtin \$\endgroup\$caird coinheringaahing– caird coinheringaahing ♦2021年03月06日 01:32:32 +00:00Commented Mar 6, 2021 at 1:32
27 Answers 27
Jelly, 2 bytes
ÆẸ
Just the builtin.
Jelly, 6 bytes
JÆN*μP
If those brownie points are attainable, it's going to be hard!
ÆN n-th prime
J for each n in 1 .. len(input).
* Raise each prime to the corresponding exponent,
μ then
P output the product.
-
\$\begingroup\$
product
is a long word, this can be shorter with2each
: Try it online! \$\endgroup\$Leo– Leo2021年03月10日 01:43:26 +00:00Commented Mar 10, 2021 at 1:43 -
1\$\begingroup\$ @Leo thanks, that's great! \$\endgroup\$rak1507– rak15072021年03月10日 01:47:00 +00:00Commented Mar 10, 2021 at 1:47
Factor + math.primes math.unicode
, (削除) 38 (削除ここまで) 33 bytes
[ dup length nprimes swap v^ Π ]
Try it online! Explanation:
dup
duplicate the input (e.g.){ 0 1 2 3 } { 0 1 2 3 }
length
find the length of a sequence{ 0 1 2 3 } 4
nprimes
generate primes given the number on top of the data stack{ 0 1 2 3 } { 2 3 5 7 }
swap
swap the top two objects on the data stack{ 2 3 5 7 } { 0 1 2 3 }
v^
vector exponentiation (component-wise){ 1 3 25 343 }
Π
find the product of a sequence25725
Factor + math.primes math.unicode
, (削除) 38 (削除ここまで) 33 bytes
[ [ length nprimes ] keep v^ Π ]
An equivalent answer using the data flow combinator keep
instead of stack shufflers. Data flow combinators generally keep the data stack more static and easier to reason about than stack shufflers.
Vyxal r
, 4 bytes
ẏǎeΠ
ẏǎeΠ
ẏ # range(0, len(input))
ǎ # nth_prime(^) // vectorises
e # ^ ** input // vectorises element-wise
Π # product(^)
The r
flag tells Vyxal to pass arguments to built-ins in reverse order. It's been around before this challenge, so I didn't add it to cheat this one time. Without it, this would be 5 bytes (ẏǎ$eΠ
)
-
1\$\begingroup\$ This is a reallly neat flag. \$\endgroup\$Razetime– Razetime2021年03月06日 07:16:17 +00:00Commented Mar 6, 2021 at 7:16
Husk, 6 bytes
Πz`^İp
Explanation
Πz`^İp implicit input
z zip the input
İp with the infinite list of primes, removing extras
^ using the power function,
` with flipped arguments.
Π take its product.
R, (削除) 83 (削除ここまで) (削除) 82 (削除ここまで) (削除) 79 (削除ここまで) (削除) 78 (削除ここまで) 68 bytes
Edit: -4 bytes thanks to Kirill L. and -1 byte thanks to Robin Ryder.
function(l,p=1){for(i in l){while(sum(!(T=T+1)%%2:T)-1)1;p=p*T^i};p}
Loops over the list l
of prime exponents, each time using while(sum(!(T=T+1)%%2:T)-1)1
to update T
to the next prime, and multiplying the cumulative product p
(initialized to 1) by T
to the power of the current exponent. Finally, returns p
.
-
\$\begingroup\$ @KirillL. - That is a super tip! Thanks! The
{}
was very unsatisfying... \$\endgroup\$Dominic van Essen– Dominic van Essen2021年03月06日 15:22:34 +00:00Commented Mar 6, 2021 at 15:22 -
-
\$\begingroup\$ @KirillL. - Thanks again! I don't know what I was thinking with that terrible loop... I've made a slight adjustment to yours (
for
->sapply
) to make it more R-like, although this didn't save any bytes... \$\endgroup\$Dominic van Essen– Dominic van Essen2021年03月06日 21:10:50 +00:00Commented Mar 6, 2021 at 21:10 -
1\$\begingroup\$ 78 bytes by changing the condition in the
while
(the same change applies to the other approach) \$\endgroup\$Robin Ryder– Robin Ryder2021年03月06日 21:39:00 +00:00Commented Mar 6, 2021 at 21:39 -
\$\begingroup\$ @RobinRyder - belated thanks! \$\endgroup\$Dominic van Essen– Dominic van Essen2021年03月07日 10:36:49 +00:00Commented Mar 7, 2021 at 10:36
Brachylog, 13 bytes
wm&l×ばつ
Function submission which dumps some garbage to STDOUT since it saves a byte over l~l&l×ばつ
or ∧ċ&l×ばつ
.
wm Create a list of unbound variables with the same length as the input.
(This also prints each element, but that's besides the point.)
<1 This list is strictly increasing,
ṗm and each of its elements is prime.
≜ Assign a value to each element.
;?z^m Raise each prime to the power of the corresponding element of the input,
×ばつ and output the product of the powers.
Without the ≜
, it completely breaks given exponents of zero--I suppose because they are mathematically eliminated from the final product?
-
1\$\begingroup\$ What’s the site policy on dumping garbage output to STDOUT? \$\endgroup\$2021年03月06日 08:52:07 +00:00Commented Mar 6, 2021 at 8:52
-
\$\begingroup\$ @cairdcoinheringaahing Looked it up on Meta before posting and it sort of looks like it's allowed \$\endgroup\$Unrelated String– Unrelated String2021年03月06日 09:02:13 +00:00Commented Mar 6, 2021 at 9:02
JavaScript, (削除) 91 (削除ここまで) (削除) 86 (削除ここまで) 84 bytes
a=>{p=[],r=1;for(i=2;0 in a;i++)r*=p.every(x=>i%x)?i**a.shift(p.push(i)):1;return r}
Saved 2 bytes thanks to Neil
Explanation
a=>{
p=[],//array of primes
r=1;//product/result
for(i=2;
0 in a;
//if 0 exists as a key in the array, then the first element exists
//and it is not empty
i++)
r*=
p.every(x=>i%x)?
//check if there is a remainder after division with each previous prime
//if so, then i is prime
i**a.shift(
p.push(i)//add to prime array, (shift ignores all arguments)
)
//multiply result by i to the power of the first
//input array element (and remove it)
:1; //multiply by 1 if i is not prime
return r
}
-
1\$\begingroup\$
r*=p.every(x=>i%x)?i**a.shift(p.push(i)):1;
saves a couple of bytes. \$\endgroup\$Neil– Neil2021年03月06日 11:39:44 +00:00Commented Mar 6, 2021 at 11:39 -
\$\begingroup\$ I am learning JavaScript and I enjoyed getting rid of the
return
, just to do some practice. The result isn't shorter, but anyway I leave it here in case someone knowledgeable is able to make it shorter. (The link is too long, I leave it below) \$\endgroup\$anotherOne– anotherOne2021年03月06日 14:00:55 +00:00Commented Mar 6, 2021 at 14:00 -
\$\begingroup\$ Try it online! \$\endgroup\$anotherOne– anotherOne2021年03月06日 14:01:16 +00:00Commented Mar 6, 2021 at 14:01
-
\$\begingroup\$ @Neil That's clever. Thanks! \$\endgroup\$Unmitigated– Unmitigated2021年03月06日 15:40:14 +00:00Commented Mar 6, 2021 at 15:40
-
\$\begingroup\$ @SheikYerbouti 84 bytes \$\endgroup\$Unmitigated– Unmitigated2021年03月06日 15:46:16 +00:00Commented Mar 6, 2021 at 15:46
Haskell, (削除) 83 69 (削除ここまで) 57 bytes
Thanks to thanks to @AZTECCO and @Unrelated String for bringing it down to 57 bytes :)
f=product.zipWith(^)(s[2..])
s(x:t)=x:s[y|y<-t,y`mod`x>0]
Edit: Realised that newlines are also one byte so putting multiple lines on a single line with semicolons doesn't change the size.
Edit #2: Realised that I don't need to take (length x)
to my list of primes, zipWith only takes how many it needs to.
Edit #3: Reduced to 57 bytes, thanks to thanks to @AZTECCO and @Unrelated String (See Comments)
Explanation:
(My solution wasn't very difficult to understand but I'm a beginner with Haskell so writing this out helps me xD)
A more readable version would be:
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x > 0]
primes = sieve [2..]
applyExponents x = zipWith (^) primes x
reconstruct = product . applyExponents
Recursive function used to generate a list of primes---use list comprehension to remove multiples of the last prime inserted into the list.
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x > 0]
Apply recursive sieve function to an infinite list of natural numbers from 2 onwards to get an infinite list of primes.
primes = sieve [2..]
(削除) Use Use zipWith to apply the correct exponent to each prime number.take (length x)
to evaluate the list of primes and get the right number of prime numbers for the length of list x. (削除ここまで)
applyExponents x = zipWith (^) p x
Then use product
to multiply the list resulting from the previous step together.
reconstruct = product . applyExponents
-
2\$\begingroup\$ A few golfs, $ saves 1 bytes by removing (), semicolon not needed, and put s[2..] directly inside f Try it online! \$\endgroup\$AZTECCO– AZTECCO2021年03月06日 18:14:11 +00:00Commented Mar 6, 2021 at 18:14
-
2\$\begingroup\$ Golfed a bit more:
product
, pointfreef
. Try it online! \$\endgroup\$Unrelated String– Unrelated String2021年03月06日 20:13:58 +00:00Commented Mar 6, 2021 at 20:13 -
2\$\begingroup\$ @AZTECCO it seems so obvious now that you said those! I guess I spent so long trying to get it to work that I let a lot slip by me (I'm really new to Haskell). Thanks a lot! :) \$\endgroup\$M. Salman Khan– M. Salman Khan2021年03月06日 21:13:51 +00:00Commented Mar 6, 2021 at 21:13
-
1\$\begingroup\$ @UnrelatedString I just had to count characters to check that
product
had less than foldl1! I didn't account for the brackets haha. Also didn't think of function composition to remove the need for the variable in the function that's genius :) Thank you! \$\endgroup\$M. Salman Khan– M. Salman Khan2021年03月06日 21:20:34 +00:00Commented Mar 6, 2021 at 21:20
C (gcc), (削除) 110 (削除ここまで) \$\cdots\$ (削除) 79 (削除ここまで) 75 bytes
Saved (削除) 5 (削除ここまで) 9 bytes thanks to xibu!!!
d;p;r;f(a,l)int*a;{for(r=p=1;l;r*=pow(p,d<2?l--,*a++:0))for(d=++p;p%--d;);}
Inputs an array of prime exponents and its length \$l\$ (because C arrays have undefined length) and returns the product of the first \$l\$ primes to those exponents.
Explanation (before some golfs)
d;p;r;f(a,l)int*a;{ // function taking an array of
// ints and its length l
for(r=p=1;l--; // loop over the array elements
// setting the product r and
// the previous prime to 1
r*=pow(p,*a++) // once we've found the next
// prime multiply r by it
// to the power of the current
// value in a
for(d=2;d>1;) // loop until we find the next
// prime, d==1 will flag this
for(d=++p; // set d to p bumped
p%--d;) // bump d down and loop
// until we find the highest
// divisor of p
d=r; // return r
} //
-
-
\$\begingroup\$ @xibu Nice one - thanks! :D \$\endgroup\$Noodle9– Noodle92021年03月06日 23:17:07 +00:00Commented Mar 6, 2021 at 23:17
-
\$\begingroup\$ I just noticed, that the last expression
d=r;
is not necessary because the assignment to r is already the last operation in the loop. \$\endgroup\$xibu– xibu2021年03月07日 00:42:42 +00:00Commented Mar 7, 2021 at 0:42 -
\$\begingroup\$ @xibu Well spotted - thanks again! :D \$\endgroup\$Noodle9– Noodle92021年03月07日 11:58:33 +00:00Commented Mar 7, 2021 at 11:58
PowerShell, 106 bytes
$s=1;while($n-lt$a.length){if(('1'*(++$i))-notmatch'^1?$|^(11+?)1円+$'){$s*=[math]::pow($i,$a[($n++)])}};$s
Uses a regex to match prime numbers, more about it here
-
2\$\begingroup\$ Wasif, please read Tips for golfing in PowerShell \$\endgroup\$mazzy– mazzy2021年03月06日 13:22:38 +00:00Commented Mar 6, 2021 at 13:22
-
\$\begingroup\$ @mazzy thanks I have read tips, the thread is very nice. I have created a thread for restricted source tips in Powershell, if you have time, you can contribute there!: codegolf.stackexchange.com/questions/220306/… \$\endgroup\$wasif– wasif2021年03月06日 17:27:36 +00:00Commented Mar 6, 2021 at 17:27
-
2
05AB1E, (削除) 6 (削除ここまで) 2 bytes
.Ó
.Ó # full program
.Ó # push the number with a prime factorization with exponents in...
# implicit input
# implicit output
Raku, 31 bytes
{[*] grep(&is-prime,^∞)Z**$_}
grep(&is-prime, ^∞)
is an infinite, lazy sequence of primes. Z**
zips that sequence with $_
, the list argument to the function, using exponentiation. Then [*]
computes the product of that sequence.
Haskell, (削除) 61 (削除ここまで) 56 bytes
f=product.zipWith(^)[x|x<-[2..],all((>0).rem x)[2..x-1]]
- saved 5 by stealing @Unrelated String advice to @M. Salman Khan answer.
APL (Dyalog Extended), (削除) 12 (削除ここまで) 11 bytes
-1 thanks to Adám
×ばつ.*⍨ ̄2⍭⍳∘≢
×ばつ.*⍨ ̄2⍭⍳∘≢
̄2⍭⍳∘≢ ⍝ the first n primes×ばつ.*⍨ ⍝ powers and product
JavaScript (ES7), (削除) 64 (削除ここまで) 58 bytes
a=>(g=d=>a+a?n%--d?g(d):(d>1||n**a.shift())*g(++n):1)(n=2)
With BigInts, 61 bytes
A version that supports large integers. Expects a list of BigInts.
a=>(g=d=>a+a?n%--d?g(d):(d<2?d:n**a.shift())*g(++n):1n)(n=2n)
Commented
a => ( // a[] = input array
g = d => // g is a recursive function taking a divisor d
a + a ? // if a[] is not empty:
n % --d ? // decrement d; if it's not a divisor of n:
g(d) // do recursive calls until it is
: // else:
( // multiply the final result by:
d > 1 || // - 1 if d is greater than 1 (n is composite)
n ** a.shift() // - the prime n raised to the power of the next
) // exponent extracted from a[] otherwise
* g(++n) // and multiply by the result of a recursive call
// with n + 1
: // else:
1 // stop the recursion and return 1
)(n = 2) // initial call to g with d = n = 2
Charcoal, 29 bytes
≔1ζFA«≦⊕ζW%⊕Π...1ζζ≦⊕ζ⊞υXζι»IΠυ
Try it online! Link is to verbose version of code. Explanation:
≔1ζ
Start finding prime numbers.
FA«
Loop over the input list.
≦⊕ζW%⊕Π...1ζζ≦⊕ζ
Increment the integer it until it's prime via Wilson's theorem.
⊞υXζι
Take the appropriate prime power.
»IΠυ
Print the product of the resulting prime powers.
05AB1E, 6 bytes
ā<ØsmP
In other words:
P sm Ø ā <
product(exponate(nth_prime_number(range(1, len(input())) - 1), input()))
Japt, 11 bytes
£Èj}iY p×ばつ
£ // Map the input array with X as items and Y as indexes to
È }iY // Y-th positive number
j // that is prime
pX // to the power of X,
×ばつ // then reduce with multiplication.
Retina, 83 bytes
$
,__
m)+`,(_+)$(?<=1円¶.+)|,(__+)2円+$
$&_
~["L$`^¶$.("|""]'_L$`(.+),(_+)
1ドル*$($.2$*
Try it online! Takes a newline-separated list. Explanation:
$
,__
Pair each element of the input array with 2 in unary.
+`,(_+)$(?<=1円¶.+)|,(__+)2円+$
$&_
Increment each unary part until it is a prime greater than the previous one.
m)`
Turn on per-line $
for all of the stages up to and including the above.
["L$`^¶$.("|""]'_L$`(.+),(_+)
1ドル*$($.2$*
Transform each pair into a repeated multiplication, so that for example 3,__
becomes three copies of 2*
i.e. 2*2*2*
while 2,___
becomes two copies of 3*
i.e. 3*3*
. Append a _
to handle the case of zero input, and prepend L$`^
and $.(
to create a Retina program that replaces the current value with the total product.
~`
Evaluate that Retina program. For example, in the case of an input of 3
2
, the resulting program is as follows:
L$`^
$.(2*2*2*3*3*_
3*_
is $(___)
and so on, with $.(
taking the final length in decimal (Retina actually optimises this and simply multiplies the values together).
R+primes, (削除) 46 (削除ここまで) 43 bytes
Exploiting the primes library
prod(primes::nth_prime(seq(a=l<-scan()))^l)
Don't try it online! (as primes is not recognised by tio.run, apparently) Here is the output on rrdr.io:
prod(primes::nth_prime(seq(a=l<-scan()))^l)
0 0 0 0 1
Read 5 items
[1] 11
prod(primes::nth_prime(seq(a=l<-scan()))^l)
2 3 1 0 0 1
Read 6 items
[1] 7020
prod(primes::nth_prime(seq(a=l<-scan()))^l)
9 0 0 1 0 0 2
Read 7 items
[1] 1035776
-
1\$\begingroup\$ I think
seq(!l)
is shorter than1:sum(1^l)
. You could also try something likeseq(a=l<-scan())
instead to get rid of the leadingl=scan()
, though I'm not sure that would be shorter or if it would even work. \$\endgroup\$Giuseppe– Giuseppe2021年03月06日 15:16:33 +00:00Commented Mar 6, 2021 at 15:16 -
\$\begingroup\$ @Giuseppe: thank you for the suggestions, both work. \$\endgroup\$Xi'an ні війні– Xi'an ні війні2021年03月06日 20:08:08 +00:00Commented Mar 6, 2021 at 20:08
Ruby -rprime
, (削除) 54 (削除ここまで) 37 bytes
A whopping 17 bytes off by Sisyphus.
->x{c=1;x.zip(Prime){|a,b|c*=b**a};c}
Wolfram Language (Mathematica), 29 bytes
(i=s=1;s*=Prime@i++^#&/@#;s)&
One character longer than @att's solution but maybe it has potential for golfing down.
Explore related questions
See similar questions with these tags.