# Calculate sum of self-exponentation

Given an array of positive integers, calculate the sum of each number raised to its own power. For example, given 4,6,7, the code needs to return $$\4^4+6^6+7^7=870455\$$.

This is code-golf, so shortest code wins.

• Welcome to Code Golf Stack Exchange! I downvoted your challenge because I find it to be overly basic and too similar to other challenges on this site, but please don't let that discourage you from trying to make another challenge! For future tasks, we have a Sandbox for Proposed Challenges that you can post your ideas to and receive feedback before getting any solutions. Commented Jul 11 at 21:57
• Related: Is it a Munchausen Number? Commented Jul 16 at 13:19

# Nibbles, 4 nibbles (2 bytes)

+.$^  Attempt This Online! +.$^     # full program
+x$^$$# with implicit variables shown + # sum of . # map over$      # each element of input
^     # x to the power of y:
$# x is each element$    #   y is each element


# Python 3.8 (pre-release),  29  26 bytes

-3 bytes thanks to Albert.Lang.

lambda l:sum(map(pow,l,l))


Try it online!

## Explanation

lambda l:                    # Anonymous lambda
sum(            )   # Sum of...
map(pow,   )    # Exponentiation of...
l,l     # element ** element for each element

• Use map and pow for -3:lambda l:sum(map(pow,l,l)) Commented Jul 11 at 22:08
• @Albert.Lang: I always thought map could only have 2 arguments... Commented Jul 11 at 22:13

# Vyxals, 1 byte

e


Try it online.

Explanation:

e   # Vectorized power with itself using the (implicit) input-list twice
s  # Sum the list
# (after which the result is output implicitly)


# Uiua, 4 bytes

/+ⁿ.


Try it

/+    # Sum of
ⁿ   # each to the power of
.  # itself


# 05AB1E, 2 bytes

mO


Try it online.

Explanation:

m   # Take the power of each value in the (implicit) input-list with each value in
# the (implicit) input-list at the same position
O  # Sum those
# (after which this sum is output implicitly as result)


# Whitespace, 115 bytes

[S S S N
_Push_sum=0][N
S S N
_Create_Label_OUTER_LOOP][S N
S _Duplicate_sum][S N
S _Duplicate_sum][T N
T   T   _Read_STDIN_as_Integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][N
T   S T N
_If_0_Jump_to_Label_PRINT][S N
S _Duplicate_input][S N
S _Duplicate_input][N
S S S N
_Create_Label_INNER_LOOP][S S S T   N
_Push_1][T  S S T   _Subtract_top_two][S N
S _Duplicate][N
T   S S S N
_If_0_Jump_to_Label_RETURN][S N
T   _Swap_top_two][S T  S S T   S N
_Copy_0-based_2nd_input_to_top][T   S S N
_Multiply_top_two][S N
T   _Swap_top_two][N
S N
S N
_Jump_to_INNER_LOOP][N
S S S S N
_Create_Label_RETURN][S N
N
T   _Swap_top_two][S N
N
S N
N
_Jump_to_OUTER_LOOP][N
S S T   N
_Create_Label_PRINT][S N
N
S T _Print_as_Integer]


Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Since Whitespace can only read input one character/integer at a time, the input must contain a trailing 0 so we'll know when we're done reading inputs.

Try it online (with raw spaces, tabs and new-lines only).

Explanation in pseudo-code:

Integer sum = 0
Start OUTER_LOOP:
Integer input = Read STDIN as integer
If (input == 0):
Integer product = input
Integer count = input
Start INNER_LOOP:
count = count - 1
If (count == 0):
product = product * input
Go to next iteration of INNER_LOOP
RETURN:
sum = sum + product
Go to next iteration of OUTER_LOOP
PRINT:
Print sum as integer to STDOUT
(implicitly stop the program with an error: No exit defined)


# Julia 1.0, 12 bytes

~x=sum(x.^x)


Try it online!

This solution showcases how operations in Julia can be vectorized with a dot. I've redefined a single-character operator, but an anonymous function x->sum(x.^x) could also be used for the same score.

By the way, sum can accept a subfunction to be called on each element before summation. For example, if A is a vector, sum(sqrt.(x)) can be shortened to sum(sqrt,x). It's not helpful in this case, since there's no unary definition for ^, but this method has been useful for most of my solutions involving sum, often saving bytes over solutions involving count.

• I don't think it gets any shorter, but !x=x'x.^.~-x is a fun alternative at the same length
– ovs
Commented Jul 13 at 11:00

# Arturo, 19 bytes

$=>[∑map&'x->x^x]  Try it! ### Explanation $=>[]      ; a function where input is assigned to &
∑          ; sum of...
map&'x->   ; map over input and assign current elt to x
x^x        ; x to the x power


# APL(Dyalog Unicode), 4 bytes SBCS

+.*⍨


Try it on APLgolf!

# Wolfram Language (Mathematica), 8 bytes

Tr[#^#]&


Try it online! Unnamed function taking a list like {4, 6, 7} as input. The exponentiation operator ^ automatically distributes over arrays of the same length, and Tr of a one-dimensional list is its sum.

# Charcoal, 7 5 bytes

ＩΣＸθθ


Try it online! Link is to verbose version of code.

   θ    Input array
Ｘ     Vectorised raised to power
θ   Input array
Σ      Take the sum
Ｉ       Cast to string
Implicitly print


Edit: Saved 2 bytes because I forgot that Power is one of the four (five on ATO) operators that auto-vectorises if both parameters are lists.

7 bytes to take input as a string:

ＩΣＥＡＸιι


Try it online! Link is to verbose version of code. Explanation: Power auto-casts strings to integer, so I don't need to write Ｉι twice.

# Desmos, 14 bytes

f(l)=l^l.total


Try It On Desmos!

Try It On Desmos! - Prettified

# Jelly, 3 bytes

*S


Try it online!

## Explanation:

*S
*   Raise to
    its own [4,6,7] => [256, 46656, 823543]
S Sum       [256, 46656, 823543] => 870455


sum.map((^)<*>id)


Try it online!

The (^)<*>id is point-free for \x->x^x. A list-comprehension solution is the same length.

f l=sum[x^x|x<-l]


Try it online!

• If imports are allowed, sum.map(join(^)) saves one byte. Commented Jul 13 at 19:06

# sed 4.2.2-rz, 167 137 bytes

s!.*!sed -r 'h;G;:r;s/.\\n./\\n/;x;s/\\n.*//;t;:b;s/.*/\&\\n\&/m;:;t;x;s/^#//;x;tb;G;h;s/\\n(.)/\\1/g;T;s/\\n../\&/;tr'<<<'&'!e
s/\n..//g


Try it online!

This essentially calls a second instance of sed with a snipit of the script I used for this question to calculate the powers, and then concats everything together at the end.

# Factor, 14 bytes

[ dup v^ sum ]


Try it online!

=sort(sum(if(A:A,A:A^A:A)))


Uses sort as an array enabler, and if() to weed out blanks. In Google Sheets, the numeric value of a blank is zero, and the self-exponents of a blank column would thus sum up to the number of rows in the column.

# Brachylog, 7 bytes

{^↙?}ᵐ+


Try it online!

Rare use of ↙. There is a less elegant version also for 7 bytes: gjz^₎ᵐ+

### Explanation

{   }ᵐ     Map for each integer:
^           Raise to the power...
↙?         ...of itself
+    Sum


# min, 23 bytes

((dup pow ceil)map sum)


# J, 5 bytes

1#.^~


Attempt This Online!

^~, called with one argument, raises that argument to the power of itself. When that argument is an array the operation is applied to each cell.

1#. means "from base-1." As it turns out, interpreting a list of integers as the digits of a base-1 number is equivalent to summing them.

This is because #. in J doesn't care whether the digits it is given are greater than the base itself - it just treats them as any other digit, multiplying them by their place value, and summing the results. In this "base-1", the place value is always 1, so this is equivalent to just summing the array.

Thanks to Conor for showing me this trick, saving a byte over the more trivial +/@: I had earlier.

• You can use the sum-as-base-1 trick to save 1 byte here: 1#.^~, link Commented Jul 13 at 4:21
• Oh that's interesting, I've never seen that one before. I'm surprised it doesn't error out when the digits are greater than the base, but I guess this makes sense. Thanks for the tip! Commented Jul 13 at 11:26

# JavaScript (V8), 28 bytes

x=>x.reduce((a,c)=>a+c**c,0)


Try it online!

• Welcome to Code Golf, and nice first answer! You can save quite a few bytes with c**c instead of Math.pow(c,c) Commented Jul 13 at 22:47
• Thanks @emanresuA! Commented Jul 13 at 22:58

# Japt-mx, 2 bytes

pU


Try it

       :Implicit map of each U in the input array
pU     :Raise U to the power of U
:Implicit output of sum of resulting array

• Could you include an explanation of your code? Commented Jul 12 at 20:53
• @AndyLiu -m runs the program on each argument and collects the results; -x returns the sum of the program's output. pU implicitly does UpU which says raise U to the power of U. Commented Jul 13 at 16:54
• Thanks for the explanation. I don’t use Japt Commented Jul 13 at 17:11

# Forth (gforth),  103  100 bytes

-3 bytes thanks to ovs

: ^ 1 TUCK +DO OVER * LOOP * ; : s 0 SWAP DUP @ 0 DO DUP I 1+ CELLS + @ DUP ^ ROT + SWAP LOOP DROP ;


Try it online!

No exponentiation in Forth so I first define ^ word and then the s word to compute the sum.

The idea:

addrTab
\ enter the loop
...
\ exit the loop
0+Elt1^Elt1+...+EltN^EltN

• the exponentiation can be a bit shorter by running the loop for one fewer iteration: : ^ 1 TUCK +DO OVER * LOOP * ;
– ovs
Commented Jul 15 at 9:55
• @ovs great! I think +DO can be replaced by DO, no? Commented Jul 15 at 10:05
• DO would break for input 1, 1 1 DO LOOP is an infinite loop.
– ovs
Commented Jul 15 at 10:08

# J-uby, 9 bytes

:sum+~:**


Attempt This Online!

Expansion of J-uby code to standard Ruby:

:sum + ~:**                        # with spaces
->(a) {:sum.(a, &~:**)}            # (F + G).(*args) == F.(*args, &G)
->(a) {:sum.(a, {|x| (~:**).(x)})} # definition of &
->(a) {:sum.(a, {|x| :**.(x, x)})} # (~F).(x) == F.(x,x)
->(a) {a.sum {|x| x ** x}}         # :F.(x, y) == x.F(y)


# Bash, 29 bytes

for i;{
let t+=i**i
}
echo $t  use as a function or bash script. takes the array as an arbitrary number of arguments, outputs to stdout. Attempt This Online! explanation: for i;{ # in bash, if the 'in array' part is not provided to 'for elem in array', it implicitly loops over all arguments let t+=i**i # bash variables are initialized to 0, the rest is simple enough } echo$t


# Pyth, 3 bytes

s^V


Attempt This Online!

s^V­⁡​‎‎⁪⁡⁪⁠⁪⁡⁪‏‏​⁡⁠⁡‌⁢​‎‎⁪⁡⁪⁠⁪⁢⁪‏⁠‎⁪⁡⁪⁠⁪⁣⁪‏‏​⁡⁠⁡‌­
s    # ‎⁡sum of
^V  # ‎⁢vectorized power with itself using the (implicit) input-list twice
💎


Created with the help of Luminespire.

-join($args|%{'+1' "*$_"*$_})|iex  Try it online! Builds the expression as a string, e.g. +1*4*4*4*4+1*6*6*6*6*6*6+1*7*7*7*7*7*7*7  Then evaluate it # Pyt, 2 bytes ṖƩ  Try it online! Ṗ implicit input; raise each element to itself Ʃ sum the array; implicit print  # Java, 32 bytes l->l.map(x->Math.pow(x,x)).sum()  Try it online! Saved 17 bytes thanks to Kevin Cruijssen. • When a challenge asks for number or list inputs, inputting as doubles and streams is allowed by default. So if you take a DoubleStream as input, it can be just 32 bytes: l->l.map(x->Math.pow(x,x)).sum() - Try it online. Commented Jul 12 at 7:05 • @KevinCruijssen Good point. Commented Jul 13 at 5:14 # Retina, 30 bytes ~["L$^¶$.("|""L$.+
*$($&$*)_  Try it online! Explanation: L$.+


Loop over each input integer.

*$($&$*)_  Write that integer followed by a *, repeated (implicitly) that many times, then finally followed by a _. For example, 3 becomes 3*3*3*_, which is how you would calculate 3*3*3 in Retina. |""  Join the calculations together, implicitly summing them. ["L$^¶$.("  Turn the calculation into a command that replaces the input with the result of the calculation converted to decimal. (Retina 1 is clever enough not to actually do the calculation in unary if it knows that it will be converting the result to decimal.) ~ Evaluate the resulting calculation. For example, for inputs of 4, 6 and 7, the resulting calculation looks like this: L$^
$.(4*4*4*4*_6*6*6*6*6*6*_7*7*7*7*7*7*7*_  (The K command doesn't perform calculations so L$^ is the easiest way.)