-6
\$\begingroup\$

Guidelines

Task

Given two non-negative integers, find the sum of both numbers... to the power of 4.


Examples

2, 3 -> 97 (2^4 + 3^4 = 97)

14, 6 -> 39712 (14^4 + 6^4 = 39712)

0, 25 -> 390625 (0^4 + 25^4 = 390625)


Rules

  • You will only ever receive two non-negative integers as input (bonus points if you get it to work with negative integer input).
  • You can take the input however you would like (arrays, list, two separate arguments, comma-separated string)
  • You can either output your answer as a number or a string.
  • As this is code golf, the shortest answer in bytes will win.
\$\endgroup\$
14
  • 2
    \$\begingroup\$ You say two positive integers, but one of the test cases contains a 0. Also, there's not many languages that would have trouble with negative integers, given the result is the same as if they were positive. \$\endgroup\$
    – Jo King
    Feb 19, 2018 at 10:08
  • 14
    \$\begingroup\$ I've downvoted this challenge for the following reason: it is a fairly trivial, yet non-essential (such as Hello, World!) and I doubt that any interesting answers will be produced. \$\endgroup\$ Feb 19, 2018 at 12:09
  • 1
    \$\begingroup\$ Downvoted for the same reason as @cairdcoinheringaahing. \$\endgroup\$
    – Yytsi
    Feb 19, 2018 at 15:54
  • 3
    \$\begingroup\$ Upvoted because sometimes trivial challenges are fun \$\endgroup\$ Feb 19, 2018 at 18:11
  • 1
    \$\begingroup\$ @cairdcoinheringaahing Just because it is trivial, does not mean it is a bad challenge? Take a look at the CP-1610 answer, I would definitely call that interesting. It has produced interesting solutions. \$\endgroup\$
    – aimorris
    Feb 19, 2018 at 19:22

46 Answers 46

7
\$\begingroup\$

Regex πŸ‡ m (PCRE2 v10.35 or later), 10 bytes

^(?*x+){4}

Attempt This Online! - PCRE2 v10.40+

Takes its input in comma-delimited unary, as a concatenation of strings of x characters whose lengths represent the numbers, separated by , characters. (Bonus: The number of arguments is variable, not just 2.) Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)

^ anchors the expression to the beginning of each line, making it process each number in the list exactly once, thanks to the multiline flag. The result of each adds to the total (instead of multiplying the total), since they are independent matches not done in concert.

Non-atomic lookahead, added to PCRE2 in v10.34 as (*napla:...) and given the (?*...) synonym in v10.35, makes calculating \$n^k\$, where \$k\$ is a constant, very easy in πŸ‡-regex. (?*x+){4} is equivalent to (?*x+)(?*x+)(?*x+)(?*x+). Each (?*x+) essentially picks a number in \$[1,n]\$, cycling through all the values effectively independently of the others, so the number of possible choices that lead to a full match is \$n^4\$.

It would not be possible to emulate this kind of solution using lookbehind with recursion to emulate variable-length-lookbehind, because that requires using lookahead nested inside lookbehind, both of which are atomic – so only one possible match would be tried. And even if it were not for that problem, the engine will complain of "nested recursion at the same subject position", which is unavoidable.

Regex πŸ‡ (PCRE / Raku:P5), 27 bytes

(|xxx|((||){2}||)xx?)x*x*x+

Try it online! - PCRE1
Try it online! - PCRE2 v10.33 / Attempt This Online! - PCRE2 v10.40+
Try it online! - Raku (Perl 6)

(
                 # apply once with tail = N
|
    xxx          # apply once with tail = N-3
|
    ((||){2}||)  # apply 3**2+2==11 times...
    xx?          # ...with tail = N-1 or N-2
)
x*x*x+           # tail'th pentatope number

Although PCRE and Raku are the only regex engines currently capable of counting this regex's number of possible matches without their source code being patched, this regex itself only uses a POSIX ERE level of functionality, so is in theory universally compatible with all regex engines.

Lacking non-atomic lookahead, the only golf-efficient way I can think of to cause the number of possible matches to be \$n^k\$, where \$k\$ is a constant, is to decompose \$n^k\$ into a sum of \$n\$-simplex numbers. \$4\$-simplex numbers have the formula \$S_4(n)=n(n+1)(n+2)(n+3)/24\$. So what we want is to solve is:

$$n^4=aβ‹…S_4(n)+bβ‹…S_4(n-1)+cβ‹…S_4(n-2)+dβ‹…S_4(n-3)$$

for \$a,b,c,d\$. The general form of this turns out to have the \$k\$th Euler's triangle row as its solution. In the case of \$n^4\$, this is \$1,11,11,1\$.

The πŸ‡-regex for \$S_4(n)\$ is x*x*x+: Try it online!

What we need to do is have it match \$1\$ time on \$n\$, \$11\$ times on \$n-1\$, \$11\$ times on \$n-2\$, and \$1\$ time on \$n-3\$.

Multiplying the number of possible matches of a subexpression can be done simply by concatenating, for example, (|||) to multiply by \$4\$. As a standalone regex returning \$4(n+1)\$, this can simply be |||: Try it online! - note that this is \$4(n+1)\$ because an empty regex returns \$n+1\$ possible matches.

The simplest choice for multiplying by \$11\$ would be (||||||||||), but it turns out this can be optimized down to ((||){2}||), as \$11=3^2+2\$, where (||){2} is \$3^2\$ and each additional | adds \$1\$. Larger numbers can be additionally optimized by factorization. Additionally, there's expressions like (|){3,5} for \$56=2^3+2^4+2^5\$.

So, ((||){2}||)xx? is the part where it's creating \$11\$ possibilities each, ((||){2}||), in which the subsequent expression is evaluated on \$n-1\$ or \$n-2\$, using xx?.

The first several n-simplex functions are as follows, in πŸ‡-regex:

\$S_0(n)\$: ^ (returns \$1\$)
\$S_1(n)\$: x (returns \$n\$)
\$S_2(n)\$: x+ (triangular numbers)
\$S_3(n)\$: x*x+ (tetrahedral numbers)
\$S_4(n)\$: x*x*x+ (pentatope numbers)
\$S_5(n)\$: x(x*){4}
\$S_6(n)\$: x(x*){5}

The first several \$n^k\$ are as follows:

\$n^0\$: Try it online! ^
\$n^1\$: Try it online! x
\$n^2\$: Try it online! x?x+ (squares)
\$n^3\$: Try it online! (|xx|(|||)x)x*x+ (cubes)
\$n^4\$: Try it online! (|xxx|((||){2}||)xx?)x*x*x+
\$n^5\$: Try it online! x(|x{4}|x((||||){2}|)(|xx)|((|){6}||)xx)(x*){4}
\$n^6\$: Try it online! x(|x{5}|x((|){3,5}|)(|xxx)|(|)((||||){2,3}|)xxx?)(x*){5}
\$n^7\$: Try it online! x(|x{6}|x(|){3,6}(|x{4})|xx(||)((||||||){2,3}|||||)(xx)?|xxx(|){4}((||||){2,3}|))(x*){6}
\$n^8\$: Try it online! x(|x{7}|x((||){5}||||)(|x{5})|xx(||){4}((|){4,5}|||||)(|xxx)|xxx((|){8}((|){2,5}|)|||)x?)(x*){7}

Perl 5 severely undercounts the number of possible matches (Attempt This Online); see below for a workaround. But Raku's Perl 5 compatibility mode (:P5 adverb) fully evaluates every choice path (and not just due to its :exhaustive adverb – it does the same without it).

Regex πŸ‡ (Perl / PCRE / Raku:P5), 30 bytes

(|xxx|(()||||||||||)xx?)x*x*x+

Try it online! - Perl v5.28.2 / Attempt This Online! - Perl v5.36+
Try it online! - PCRE1
Try it online! - PCRE2 v10.33 / Attempt This Online! - PCRE2 v10.40+
Try it online! - Raku (Perl 6)

The part in the 27 byte version that is undercounted by Perl is ((||){2}||), the expression that multiplies possibilities by 11.

Perl forces any loop to exit after making a zero-width match (whereas PCRE only does so on loops whose quantifier has no maximum, which I think is more logical), so (||){2} needs to be changed to (||)(||), adding 1 byte.

Perl prunes a group's alternatives down to one if they are all identical, but doesn't do this if even one alternative differs from the others. So (||) needs to be changed to (()||) in both places, adding 4 bytes.

After all that, it becomes ((()||)(()||)||). But that's longer than (()||||||||||), so we use the latter instead, at just 3 bytes longer than ((||){2}||).

Regex πŸ‡ m (PCRE), 73 69 bytes

Without decomposing a fourth power into pentatope numbers, I'm pretty sure this is the best solution possible (it might golf down a tiny bit more than this, but not much):

^(?=(x*)\1{3}(xx())?(x())?)((?=\1(x*))(x+(|||)|\3(|)|\5).*(?=\7$)){4}

Try it online! - PCRE2 v10.33 / Attempt This Online! - PCRE2 v10.40+

^                    # tail = N = input number
(?=
    (x*)\1{3}        # \1 = floor(tail / 4)
    (()xx)?(()x)?    # \3,\5 = {tail % 4} in binary:
                     # \3 set|unset = 2's place digit 1|0
                     # \5 set|unset = 1's place digit 1|0
)
(
    # Manipulate the number of possible matches to be exactly \1 * 4 + \2 == N
    (?=\1(x*))       # \7 = tail - \1
    (
        x+(|||)      # Add \1 * 4 to the number of possibilities of this iteration
    |
        \3(|)|\5     # Add \3*2 + \5 (where set=1 and unset=0) to the number of
                     # possibilities of this iteration
    )
    .*(?=\7$)        # tail = \7, i.e. the next multiple of \1 down from what it
                     # was when \7 was captured above.
){4}                 # Iterate the above 4 times, such that after finishing, each
                     # iteration could have been at any one of the N states.

This method does eventually win out against simplex decomposition:

1: x
β€‡β€ˆ x

2: x?x+
β€‡β€ˆ ^(?=(x*)\1(x()|))\2(x+(|)|\3).*(?=\1$)(?4)

3: (|xx|(|||)x)x*x+
β€‡β€ˆ ^(?=(x*)\1\1(x())?(x())?)((?=\1(x*))(x+(||)|\3|\5).*(?=\7$)){3}

4: (|xxx|((||){2}||)xx?)x*x*x+
β€‡β€ˆ ^(?=(x*)\1{3}(xx())?(x())?)((?=\1(x*))(x+(|||)|\3(|)|\5).*(?=\7$)){4}

5: x(|x{4}|x((||||){2}|)(|xx)|((|){6}||)xx)(x*){4}
β€‡β€ˆ ^(?=(x*)\1{4}(xx())?(x())?(x())?)((?=\1(x*))(x+(||||)|\3(|)|\5|\7).*(?=\9$)){5}

6: x(|x{5}|x((|){3,5}|)(|xxx)|(|)((||||){2,3}|)xxx?)(x*){5}
β€‡β€ˆ ^(?=(x*)\1{5}(xx())?(xx())?(x())?)((?=\1(x*))(x+(|||||)|\3(|)|\5(|)|\7).*(?=\9$)){6}

7: x(|x{6}|x(|){3,6}(|x{4})|xx(||)((||||||){2,3}|||||)(|xx)|xxx(|){4}((||||){2,3}|))(x*){6}
β€‡β€ˆ ^(?=(x*)\1{6}(xxx())?(xx())?(x())?)((?=\1(x*))(x+(||||||)|\3(||)|\5(|)|\7).*(?=\9$)){7}

8: x(|x{7}|x((||){5}||||)(|x{5})|xx(||){4}((|){4,5}|||||)(|xxx)|xxx((|){8}((|){2,5}|)|||)x?)(x*){7}
β€‡β€ˆ ^(?=(x*)\1{7}(x{4}())?(xx())?(x())?)((?=\1(x*))(x+(|){3}|\3(|||)|\5(|)|\7).*(?=\9$)){8}

\$\endgroup\$
6
+100
\$\begingroup\$

CP-1610 assembly, 30 DECLEs = 38 bytes

Let's try this on a processor lacking a multiply instruction. This code is intended to be run on an Intellivision.

CP-1610 instructions are encoded with 10-bit values, known as 'DECLE' s. This subroutine is 30 DECLEs long, starting at $4808 and ending at $4825.

Takes input in registers R0 and R3. Saves the result in R2.

                              ROMW  10            ; use 10-bit ROM
                              ORG   $4800         ; map program at address $4800

4800  02B8 000E               MVII  #14,    R0    ; example call
4802  02BB 0006               MVII  #6,     R3
4804  0004 0148 0008          CALL  addX4Y4
4807  0017                    DECR  PC            ; loop forever

4808  0275            addX4Y4 PSHR  R5            ; push the return address
4809  0004 0148 001A          CALL  square        ; compute R2 = R0^2
480C  0004 0148 0019          CALL  square2       ; compute R2 = R2^2
480F  0272                    PSHR  R2            ; push this result on the stack
4810  0098                    MOVR  R3,     R0    ; compute R2 = R3^2
4811  0004 0148 001A          CALL  square
4814  0004 0148 0019          CALL  square2       ; compute R2 = R2^2
4817  02F2                    ADD@  R6,     R2    ; add this result to the intermediate one
4818  02B7                    PULR  PC            ; return

4819  0090            square2 MOVR  R2,     R0    ; copy R2 to R0
481A  0081            square  MOVR  R0,     R1    ; copy R0 to R1
481B  01D2                    CLRR  R2            ; initialize R2 = result
481C  0200 0002               B     halve         ; start by halving R1
481E  00C2            add     ADDR  R0,     R2    ; add R0 to R2
481F  0048            loop    SLL   R0            ; double R0
4820  0079            halve   SARC  R1            ; halve R1
4821  0221 0004               BC    add           ; was the LSB set?
4823  022C 0005               BNEQ  loop          ; is R1 now equal to zero?
4825  00AF                    JR    R5            ; return

Example run

Running the above code (with R0 = 14 and R3 = 6) gives:

> b 4807
Set breakpoint at $4807
> r
Hit breakpoint at $4807
 0900 0000 9B20 0006 01FE 4817 02F1 4807 S-----iq  DECR R7
           ^^^^

R2 is set to $9B20, which is 39712 in decimal.

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

Perl, 12 bytes

Includes +1 for p

Works for 1 or more numbers each given on a separate line on STDIN

(echo 2; echo 3) | perl -pe '$\+=$_**4}{'
\$\endgroup\$
4
\$\begingroup\$

Haskell, 11 bytes

sum.map(^4)

This is a function that takes the parameters as a list.

Try it online!

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Same bytecount: a#b=a^4+b^4 \$\endgroup\$ Feb 19, 2018 at 15:02
3
\$\begingroup\$

><>, 11 bytes

:*:*$:*:*+n

Try it online!

Takes values through the -v flag. Dupe and multipy, dupe and multiply, and repeat with the other value before adding the two together and printing.

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

Retina, 9 bytes

.+
****
_

Try it online!

Input should be linefeed-separated.

Explanation

.+
****

* is Retina's repetition operator. It has implicit operands $& and _, respectively, so the substitution pattern is short for $&*$&*$&*$&*_. It's also right-associative, if the regex matches a decimal number n, this generates a string of n4 underscores (i.e. a unary representation of the fourth power of n).

_

To sum the two results and convert the sum back to decimal, we simply count the number of underscores in the string.

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

Japt, 3 bytes

Takes input as an array of integers; can handle negatives and more than 2 integers at a time. Add N at the beginning to take input as individual integers.

xp4

Try it


Explanation

p4 raises each element to the power of 4 and x reduces by addition.

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

Pyt, 2 bytes

⁴Ʃ

Try it online!

Takes input as a list.

\$\endgroup\$
1
  • \$\begingroup\$ Knew there would be a language with a built-in for **4, congrats. \$\endgroup\$ Feb 20, 2018 at 16:50
2
\$\begingroup\$

APL (Dyalog Unicode), 5 bytesSBCS

Anonymous tacit prefix function. Takes a list as argument. The list may have any length and contain any numbers, even complex ones.

+.*∘4

Try it online!

+.* is a variant on matrix product, +.Γ— as follows: a b+.Γ—c d is (aΓ—c)+(bΓ—d) and a b+.Γ—c is (aΓ—c)+(bΓ—c). So a b+.*c is (a*c)+(b*c). * is power.

∘4 curry four as right argument. This results in a monadic function (a*4)+(b*4).

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

J, 7 6 bytes

-1 byte thanks to AdΓ‘m

1#.^&4

Try it online!

Works for lists with arbitrary length

^&4 - each item of the list to the 4-th power

1#. - sum of all 4-th powers by base-1 conversion

Try it online!

Alternative

J, 7 bytes

+/ .^4:

This is a variant of the matrix product, analogue of AdΓ‘m's APL solution

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 6 bytes: 1#.^&4 \$\endgroup\$
    – Adám
    Feb 19, 2018 at 10:34
  • \$\begingroup\$ @Adám Thanks, I forgot to try to add up the numbers by base-1 conversion. \$\endgroup\$ Feb 19, 2018 at 11:09
2
\$\begingroup\$

Python 3, 20 bytes

lambda x,y:x**4+y**4
\$\endgroup\$
3
  • \$\begingroup\$ You can remove the assignment to f as this isn't a recursive function. \$\endgroup\$
    – Shaggy
    Feb 19, 2018 at 11:56
  • \$\begingroup\$ @Shaggy Maybe I'm confused but how else would my answer take any input? Wouldn't I then be defining something that is essentially 'lost' right after being interpreted? It's not like I can feed input in via args, for example. Or it is normal in codegolf that those bytes 'f=' are not counted? \$\endgroup\$
    – linemade
    Feb 19, 2018 at 12:27
  • \$\begingroup\$ What I meant was: you don't need to include it in your byte count. Anonymous functions/lambdas are valid. \$\endgroup\$
    – Shaggy
    Feb 19, 2018 at 13:00
2
\$\begingroup\$

MATL, 3 bytes

K^s

Try it online!

This can handle more than two input values, as well as negative inputs.

Explanation:

Fasten your seat belts, this might blow your mind!

       % Implicit input
K      % Push literal 4
 ^     % Raise each element of the input vector to the 4th power
  s    % Sum

Also works:

4^s    % Push 4 and raise input to it, then sum
UUs    % Square input twice, then sum
\$\endgroup\$
0
1
\$\begingroup\$

JavaScript (ES7), 15 bytes

Does exactly what it says on the tin.

a=>b=>a**4+b**4

Test cases

let f =

a=>b=>a**4+b**4

console.log(f(2)(3))
console.log(f(14)(6))
console.log(f(0)(25))

\$\endgroup\$
1
  • \$\begingroup\$ Ah, nuts! \$\endgroup\$
    – Shaggy
    Feb 19, 2018 at 10:03
1
\$\begingroup\$

05AB1E, 3 bytes

4mO

Try it online!

Explanation

4m    # raise each to the power of 4
  O   # sum
\$\endgroup\$
1
\$\begingroup\$

Julia, 11 bytes

a$b=a^4+b^4

Try it online!


Julia, 12 bytes

!a=sum(a.^4)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Excel, 10 bytes

=A1^4+B1^4

Nothing to see here.

\$\endgroup\$
1
\$\begingroup\$

C (gcc), 26 bytes

f(a,b){a=a*a*a*a+b*b*b*b;}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C, C++ => 29 bytes

-1 byte thanks to Jonathan Frech

#define Q(a,b)a*a*a*a+b*b*b*b

Test cases :

#include <stdio.h>
int main() {
    printf("Q(%d,%d) = %d\n", 2, 3, Q(2, 3));
    printf("Q(%d,%d) = %d\n", 14, 6, Q(14, 6));
    printf("Q(%d,%d) = %d\n", 0, 25, Q(0, 25));
}
\$\endgroup\$
1
  • \$\begingroup\$ Could you not drop the space in ) a? \$\endgroup\$ Feb 19, 2018 at 11:07
1
\$\begingroup\$

Jelly, 3 bytes

*4S

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Triangularity, 31 bytes

...)...
..IEM..
.)4s^}.
u......

Try it online!

\$\endgroup\$
1
\$\begingroup\$

C (gcc), 0 + 24 bytes

Compile this code

main(){
    printf("%d\n",x(2,3));
    printf("%d\n",x(14,6));
    printf("%d\n",x(0,25));
}

With this flag:

-D=x(a,b)a*a*a*a+b*b*b*b

Try it online! (GCC Tio)
Try it online! (Bash Compile example)

\$\endgroup\$
1
\$\begingroup\$

R, 16 bytes

pryr::f(x^4+y^4)

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Ruby, 16 bytes

->a,b{a**4+b**4}

Try It Online!

\$\endgroup\$
1
\$\begingroup\$

Java 8, 21 bytes

a->b->a*a*a*a+b*b*b*b

Try it online.

\$\endgroup\$
1
\$\begingroup\$

Perl 6, 9 bytes

*⁴+*⁴

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ @EsolangingFruit The problem is that along with * WhateverCode lambdas there are also ** HyperWhatever lambdas; so it would have to be written as *Β **4+*Β **4, or else it would would be seen as **Β *4+**Β *4 which doesn't work. ((**⁴)(2,3) results in (16,18)) \$\endgroup\$ Feb 19, 2018 at 17:59
  • \$\begingroup\$ @BradGilbertb2gills I guess that makes sense. Why am I surprised Perl supports Unicode superscript exponents? \$\endgroup\$ Feb 20, 2018 at 1:01
1
\$\begingroup\$

Pyth, 5

sm^d4

Online test.

  ^d4     # lambda to take 4th power
     Q    # implicit input
 m        # map lambda over input
s         # sum
\$\endgroup\$
1
\$\begingroup\$

Attache, 8 bytes

Sum@`^&4

Try it online!

Takes input as a pair of integers.

Explanation

This is a composition of two functions:

  • Sum
  • `^&4

The first executed is `^&4, which is equivalent to:

`^&4
RBond[`^, 4]
RBond[{_1 ^ _2}, 4]
{_1 ^ 4}

That is, a function that raises its argument to the fourth power. This vectorizes over the input array. Then, Sum takes the sum of these elements.

Alternative approaches

Sum@`^&4@V    ?? 11 bytes, input is two arguments
{Sum[_^4]}    ?? 11 bytes, input is array
{_^4+_2^4}    ?? 11 bytes, input is two arguments
\$\endgroup\$
1
\$\begingroup\$

Pyramid Scheme, 220 bytes

           ^
          / \
         /   \
        /  +  \
       /       \
      ^---------^
     /^\       /^\
    ^---^     ^---^
   /#\ /4\   /#\ /4\
  ^--- ---  ^--- ---
 /l\       /l\
/ine\     /ine\
-----     -----

Try it online!

line pyramids obtain a line from STDIN, # pyramids cast their arguments into numbers, ^ pyramids perform exponentiation, and the + pyramid adds two things together.

\$\endgroup\$
1
\$\begingroup\$

Minkolang 0.15, 10 bytes

$n4;r4;+N.

Try it here.

Explanation

$n4;r4;+N.
$n           take all input as numbers     [a, b]
  4;         raise to the fourth           [a, b^4]
    r        reverse stack                 [b^4, a]
     4;      raise to the fourth           [b^4, a^4]
       +     add                           [b^4 + a^4]
        N    output                        []
         .   terminate
\$\endgroup\$
1
\$\begingroup\$

D, 25 bytes

(int x,int y)=>x^^4+y^^4;

Try it online!

A simple lambda that performs exponentiation on each of its arguments, with ^^ being the exponentiation operator.

\$\endgroup\$

Your Answer

By clicking β€œPost Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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