7
\$\begingroup\$

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.

\$\endgroup\$
3
  • 9
    \$\begingroup\$ 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. \$\endgroup\$ Commented Jul 11 at 21:57
  • \$\begingroup\$ @noodleperson Thank you for your advice! I will try to follow your suggestions in the future. \$\endgroup\$
    – Andy Liu
    Commented Jul 13 at 2:55
  • 1
    \$\begingroup\$ Related: Is it a Munchausen Number? \$\endgroup\$
    – Giuseppe
    Commented Jul 16 at 13:19

39 Answers 39

6
\$\begingroup\$

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
\$\endgroup\$
6
\$\begingroup\$

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
\$\endgroup\$
2
  • 3
    \$\begingroup\$ Use map and pow for -3:lambda l:sum(map(pow,l,l)) \$\endgroup\$ Commented Jul 11 at 22:08
  • 2
    \$\begingroup\$ @Albert.Lang: I always thought map could only have 2 arguments... \$\endgroup\$ Commented Jul 11 at 22:13
6
\$\begingroup\$

Vyxal s, 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)
\$\endgroup\$
5
\$\begingroup\$

Uiua, 4 bytes

/+ⁿ.

Try it

/+    # Sum of
  ⁿ   # each to the power of
   .  # itself
\$\endgroup\$
5
\$\begingroup\$

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)
\$\endgroup\$
5
\$\begingroup\$

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
_Discard_top_0][S N
T   _Swap_top_two][S N
N
_Discard_top_input][T   S S S _Add_top_two][N
S N
N
_Jump_to_OUTER_LOOP][N
S S T   N
_Create_Label_PRINT][S N
N
_Discard_top_0][T   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):
    Stop OUTER_LOOP, and jump to PRINT
  Integer product = input
  Integer count = input
  Start INNER_LOOP:
    count = count - 1
    If (count == 0):
      Stop INNER_LOOP, and jump to RETURN
    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)
\$\endgroup\$
5
\$\begingroup\$

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.

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

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
\$\endgroup\$
4
\$\begingroup\$

APL(Dyalog Unicode), 4 bytes SBCS

+.*⍨

Try it on APLgolf!

\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Charcoal, 7 5 bytes

IΣXθθ

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

   θ    Input array
  X     Vectorised raised to power
    θ   Input array
 Σ      Take the sum
I       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:

IΣEAXιι

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

\$\endgroup\$
4
\$\begingroup\$

Desmos, 14 bytes

f(l)=l^l.total

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Haskell, 17 bytes

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!

\$\endgroup\$
1
  • \$\begingroup\$ If imports are allowed, sum.map(join(^)) saves one byte. \$\endgroup\$ Commented Jul 13 at 19:06
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Factor, 14 bytes

[ dup v^ sum ]

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Google Sheets, 27 bytes

=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.

screenshot

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

min, 23 bytes

((dup pow ceil)map sum)

enter image description here

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ You can use the sum-as-base-1 trick to save 1 byte here: 1#.^~, link \$\endgroup\$ Commented Jul 13 at 4:21
  • 1
    \$\begingroup\$ 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! \$\endgroup\$ Commented Jul 13 at 11:26
3
\$\begingroup\$

JavaScript (V8), 28 bytes

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

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! You can save quite a few bytes with c**c instead of Math.pow(c,c) \$\endgroup\$
    – emanresu A
    Commented Jul 13 at 22:47
  • \$\begingroup\$ Thanks @emanresuA! \$\endgroup\$ Commented Jul 13 at 22:58
3
\$\begingroup\$

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
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Could you include an explanation of your code? \$\endgroup\$
    – Andy Liu
    Commented Jul 12 at 20:53
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ Commented Jul 13 at 16:54
  • \$\begingroup\$ Thanks for the explanation. I don’t use Japt \$\endgroup\$
    – Andy Liu
    Commented Jul 13 at 17:11
3
\$\begingroup\$

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
0 addrTab
\ enter the loop
0 addrTab addrElt1
0 addrTab Elt1
0 addrTab Elt1 Elt1
0 addrTab Elt1^Elt1
addTab 0+Elt1^Elt1
0+Elt1^Elt1 addrTab
... 
0+Elt1^Elt1+...+EltN^EltN addrTab
\ exit the loop
0+Elt1^Elt1+...+EltN^EltN
\$\endgroup\$
3
  • 1
    \$\begingroup\$ the exponentiation can be a bit shorter by running the loop for one fewer iteration: : ^ 1 TUCK +DO OVER * LOOP * ; \$\endgroup\$
    – ovs
    Commented Jul 15 at 9:55
  • \$\begingroup\$ @ovs great! I think +DO can be replaced by DO, no? \$\endgroup\$
    – david
    Commented Jul 15 at 10:05
  • 1
    \$\begingroup\$ DO would break for input 1, 1 1 DO LOOP is an infinite loop. \$\endgroup\$
    – ovs
    Commented Jul 15 at 10:08
3
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

PowerShell Core, 33 bytes

-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

\$\endgroup\$
2
\$\begingroup\$

Pyt, 2 bytes

ṖƩ

Try it online!

Ṗ              implicit input; raise each element to itself
 Ʃ             sum the array; implicit print
\$\endgroup\$
2
\$\begingroup\$

Java, 32 bytes

l->l.map(x->Math.pow(x,x)).sum()

Try it online!

Saved 17 bytes thanks to Kevin Cruijssen.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Jul 12 at 7:05
  • \$\begingroup\$ @KevinCruijssen Good point. \$\endgroup\$ Commented Jul 13 at 5:14
2
\$\begingroup\$

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.)

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.