g | x | w | all
Bytes Lang Time Link
053AWK250328T201508Zxrs
075SAKO250324T164300ZAcrimori
023APLNARS250115T142916ZRosario
037Regex ECMAScript or better220210T055934ZDeadcode
076BrainChild250115T014737ZATaco
011Pyth240812T080043ZGlory2Uk
033Haskell240812T132244Zxnor
006Thunno 2230818T105356ZThe Thon
047Desmos220503T031934Zfireflam
037k ngn/k220220T190936Zsugarfi
023Julia 1.0220216T225614Zamelies
035Julia220215T211427ZDavid Sc
066F#220213T234357ZCiaran_M
043MATLAB220210T194502Zrobbie c
026Retina 0.8.2220207T100511ZNeil
071JavaScript V8220210T053912ZThatCool
037R220209T102919ZRobin Ry
109tinylisp220208T184851ZDLosc
125tinylisp220207T161237ZGiuseppe
025Octave220208T100311ZCG.
00605AB1E220207T084222ZKevin Cr
038Haskell220207T202533ZAZTECCO
008MATL220207T175751ZSundar R
052Desmos220208T020212ZAiden Ch
064Excel220208T001525ZAxuary
033JavaScript Node.js220207T093336Zdingledo
053C gcc220207T092853Zsinvec
005Vyxal RM220207T085028Zemanresu
006Jelly220207T170707Zcaird co
049Python 3220207T120348Zloopy wa
015Burlesque220207T133809ZDeathInc
039R220207T090312Zpajonk
014APLDyalog Unicode220207T111455Zuser1069
033R220207T101812ZDominic
019Charcoal220207T100755ZNeil
063Python 3.8 prerelease220207T094117Zsolid.py
044Ruby220207T092759ZG B
059Python 3220207T085839ZJitse
015Wolfram Language Mathematica220207T084527Zalephalp
007Brachylog220207T084213ZFatalize

AWK, 53 bytes

{for(;i<=$1;i++)for(j=-1;j++<$1;)j^2+i^2-$1||g=1}$0=g

Attempt This Online!

It's not fast when you get to bigger numbers as it's exhaustive and doesn't short when it finds one.

{for(;i<=$1;i++)   # all numbers up to input
for(j=-1;j++<$1;)  # all numbers up to input
j^2+i^2-$1||g=1}   # it's not a good sum or set output to 1
$0=g               # prints a one if a good sum is found

SAKO, 75 bytes

PODPROGRAM:F(N)
**)LINIIENT(A*2+B*2-N)
POWTORZ:A=0(1)N
POWTORZ:B=0(1)N
WROC

Outputs 0 carriage returns for falsy and a positive number of carriage returns for truthy. An easy way to check how many were printed is by using this command: ./filename | grep $'\r' -c.

Full programme version, 77 bytes

CZYTAJ:N
**1)LINIIENT(A*2+B*2-N)
POWTORZ:A=0(1)N
POWTORZ:B=0(1)N
STOP1
KONIEC

APL(NARS), 23 chars

{⍵=0:1⋄∨/0=1∣√⍵-×⍨⍳⌊√⍵}

if input is n>=0, return 1 if n=0 or if n!=0, for some a in 1..√n, sqrt(n-a^2) is one integer. Could be this 15 if one can apply "0 is true", "!=0 is false" and input>0

{×/1∣√⍵-×⍨⍳⌊√⍵}

Test:

 (0,⍳100)/⍨ {⍵=0:1⋄∨/0=1∣√⍵-×⍨⍳⌊√⍵}¨0,⍳100
0 1 2 4 5 8 9 10 13 16 17 18 20 25 26 29 32 34 36 37 40 41 45 49 50 52 53 58 61 64 65 68 72 
  73 74 80 81 82 85 89 90 97 98 100 

Regex (ECMAScript or better), 37 bytes

^((x(x*))(?=.*(?=\2*$)(\3+$))\4|){2}$

Try it online! - ECMAScript
Try it online! - Perl
Try it online! - Java
Try it online! - Python
Try it online! - Ruby
Try it online! - PCRE
Try it online! - .NET

Takes its input in unary, as a string of x characters whose length represents the number. Uses a variant of the multiplication/squaring algorithm explained in this post.

Commented and indented:

^                  # tail = N = input number
(                  # subtract a perfect square from tail
    # subtract a nonzero perfect square from tail
    (x(x*))        # \2 = any positive integer; \3 = \2-1; tail -= \2
    (?=
        .*         # find the smallest value of tail that satisfies the following
        (?=\2*$)   # assert \2 divides tail
        (\3+$)     # assert \3 divides tail at least once; \4 = \2*\2 - \2
    )
    \4             # along with "tail -= \2" above, acts as "tail -= \2*\2"
|
    # or just subtract 0 from tail
){2}               # do this twice
$                  # assert that tail == 0

This can be generalized to sums of any number of squares by changing the 2 in {2} to the desired count.

Regex (Perl / Java / PCRE2 v10.34 or later / .NET), 21 20 bytes

^(\1?(\2xx|^x)*){2}$

Try it online! / Attempt This Online! - Perl
Try it online! / Attempt This Online! - Java
Try it on regex101 / Attempt This Online! - PCRE2
Try it online! - .NET

^                  # tail = N = input number
(                  # The following will be captured in \1
    \1?            # Optionally subtract the previous perfect square from tail
    (\2xx|^x)*     # If on the first iteration, subtract a perfect square from tail;
                   # if on the second iteration and "\1?" was evaluated once,
                   # combines with it to subtract a perfect square from tail that
                   # is greater than or equal to the previous one; if "\1?" was
                   # evaluated zero times, this adjusts the first perfect square
                   # subtracted, optionally increasing it to a larger one, which
                   # effectively makes the "other" perfect square zero.
){2}               # Iterate this twice
$                  # Assert that tail == 0

Regex (ECMAScript or better), 75 71 70 bytes

^((?=(xx+?)\2*$)((?=\2+$)(?=(x+)\B((\4{4})*\4?$|)(\4*$))\7\5?){2})*x?$

Try it online! - ECMAScript
Attempt This Online - PCRE2

Uses the Sum of two squares theorem. Although this is much longer than the 37 byte version, it's also much faster.

^                # tail = N = input number
(
    (?=(xx+?)\2*$)   # \2 = smallest prime factor of tail
    # If \2 ≡ 3 mod 4, then the following {2} loop must divide tail by
    # \2 exactly twice, meaning with multiple outer loop iterations, an
    # even number of times in total. Otherwise, it can divide tail by \2
    # once or zero times, i.e. any even or odd number of times in total.
    (
        (?=\2+$)         # Assert \2 divides tail
        (?=
            (x+)         # \4 = largest proper divisor of tail
                         #    = tail / \2
            \B           # Assert tail != 0 (effectively)
            (            # \5 = tail - \4 if \2 % 4 != 3,
                         # else \5 = 0
                (\4{4})* # tail -= \4 * 4 * {arbitrary number}
                \4?$     # Assert tail == \4 or tail == 0;
                         # tail = 0
            |
            )
            (\4*$)       # \7 = tail; assert \4 divides tail
        )
        \7               # tail -= \7
        \5?              # tail -= \5, optionally
    ){2}             # Iterate twice
)*               # Iterate as many times as possible, min zero
x?$              # Assert tail ≤ 1

BrainChild, 76 bytes

int n->int=>{int a=0while a<=n{int b=0while b<=a if(n==a*a+b*b++)n=0a++}!n;}

Try It Online!

Ungolfed with comments

int n->int=>{                       // Define a function taking 1 int and returning an int. Explicitely stating return type ends up faster than using `return` later.
    int a=0
    while a<=n{                     // Standard for(a=0; a<=n; a++)
        int b=0
        while b<=a                  // for(b=0; b<=a
            if(n==a*a+b*b++)        // We increment b as we check if a^2+b^2 to avoid needing blocks
                n=0                 // Instead of returning, we just set n to 0, as n=0 is a known truthy state.
        a++                         // And if n is zero, everything conveniently exists early.
    }
    !n;                             // if by the end, n is non-zero, this returns 0, or 1 otherwise.
}

Pyth, 12 11 bytes

}Q+M^^R2hQ2

Try it online!

Test cases

I have a feeling that pyth can do better. 11 Bytes, you know, it's in comparison to other golfing languages a lot.

The algorithm is not different from the published answers and, consequently, the performance is not sufficient to calculate the two largest test values in less than 60 sec.

Commented version:

}Q           # check whether the input value Q is within:
  +M         # the sums 
    ^      2 # of cartesian product with itself
     ^R2     # of squared
        hQ   # range of 0..Q

Haskell, 33 bytes

f n=and[gcd(k^2)n/=k|k<-[3,7..n]]

Try it online!

Checks that all \$k\$ that are \$3 \bmod 4\$ have \$\gcd(k^2,n)\neq k\$. This comes from the characterization of sums of two squares as numbers whose prime factorization doesn't have any \$3 \bmod 4\$ prime raised to an odd power. If such a \$p^a\$ appears in the factorization, then \$p^a \ \equiv 3 \bmod 4\$, and \$k=p^a\$ will fail the condition.

Outputting True/False reversed could save a byte by using or rather than and.

Thunno 2, 6 bytes

Ė2Ṛ²ʂƇ

Try it online!

Very slow for large inputs.

Explanation

Ė2Ṛ²ʂƇ  # Implicit input
Ė       # Push [0..input]
 2Ṛ     # Combinations with
        # replacement with
        # a length of two
   ²    # Square (vectorised)
    ʂ   # Sum each inner list
     Ƈ  # Contains the input?
        # Implicit output

Desmos, 47 bytes


f(n)=\prod_{a=0}^n\prod_{b=0}^n\{aa+bb=n:0,1\}

The leading newline is necessary for the piecewise to paste properly.

Outputs 0 for truthy and 1 for falsey.

Try it on Desmos!

The trick didn't work, maybe due to the \{aa+bb=n:0,1\} piecewise. Avoiding it with sign(aa+bb-n)^2 or 0^{(aa+bb-n)^2} ended up longer.

k (ngn/k), 37 bytes

c:{0<#&x{x=+/y}/:+{(%x)=_%x}#'!2#1+x}

try it in the ngn/k repl

Julia 1.0, 28 23 bytes

~n=n∈(N=(0:n).^2).+N'

Try it online!

Based on David Scholz’s solution.

Thanks to dingledooper for shaving 5 bytes

Julia, 49 35 bytes

~n=1 in[i^2+j^2==n for i=0:n,j=0:n]

Try it online!

Thanks to MarcMush we can save a lot more! We can also replace f(n) with the slightly shorter version ~n!

F#, 66 bytes

let a t=Seq.allPairs[0..t][0..t]|>Seq.tryFind(fun(f,s)->f*f+s*s=t)

Try it online!

Straight-forward: create two lists from 0 to total, Seq.allPairs gets the Cartesian product between the two, and Seq.tryFind tries to find the pair that, when squared and added together, equals the total t.

MATLAB, 43 bytes

o=@(x)any(~mod(sqrt(x-(0:(x/2)^.5).^2),1));

taking advantage of vectorized code to search from 0 to sqrt(x/2), checking sqrt(x - i^2) is an integer with mod([],1)

Try it online!

Retina 0.8.2, 31 26 bytes

.+
$*
^((^1|11\2)*\1?){2}$

Try it online! Link includes test cases. Edit: Saved 5 bytes thanks to @Deadcode. Explanation: ^((^1|11\2)*) matches a square number at the beginning of the string. Repeating the expression with {2} does not in itself change this, but it allows the use of \1? to add a square number matched on the first iteration. (The first stage simply converts the decimal input to unary.)

JavaScript (V8), 71 bytes

f=n=>(m=n)?[...Array(++m*m).keys()].some(i=>(i%n)**2+(~~(i/n))**2==n):0

Try it online!

Not great but might as well post it since I spent an hour trying.

R, 37 bytes

function(n,k=2^(0:n)^2)2^n%in%(k%o%k)

Try it online!

This checks whether \$2^n\$ can be written as \$2^{a^2}\times 2^{b^2}\$. This will rapidly run into numerical issues, but is shorter than pajonk's similar answer because we can then use %o% instead of outer. Note that Dominic's R answer remains 4 bytes shorter.

tinylisp, 125 117 109 bytes

(d X(q((N I)(i(l N 1)N(X(s N I)(a I 2
(d S(q((I N)(i(a(X I 1)(X(s N I)1))(i(l N I)0(S(a I 1)N))1
(q((N)(S 0 N

The last line is an anonymous function that takes a number and returns 1 if it is the sum of two squares, 0 otherwise. Try it online!

Ungolfed/explanation

Look, ma, no library!

First, we define a helper function X that takes a number N and determines if it is (not) a square. A perfect square is the sum of consecutive odd numbers; therefore, subtracting the sum of the first several odd numbers from N (for an appropriate value of "several") will result in 0 if N is square. Thus, we recurse over increasingly large odd numbers (which we track as I) and subtract each one from N until N equals 0 (in which case N is square) or N is less than 0 (in which case N is not square):

(def not-square?        ; Define not-square?
  (lambda (N I)         ; as a function of two arguments:
    (if (less? N 1)     ;  If N is less than 1,
      N                 ;  return N (0 if square, negative if not square)
      (not-square?      ;  Else, recurse with these arguments:
        (sub2 N I)      ;   New N is previous N minus current odd number
        (add2 I 2)))))  ;   New I is the next odd number

Next, we'll define a function S that determines whether a number N is the sum of two squares. Our algorithm here is to recurse over integers I starting at 0: if I is not square, or N minus I is not square, try the next I until N is less than I, at which point N cannot be the sum of two squares. On the other hand, if I and N minus I are both square, then N is the sum of two squares.

(def sum-squares?           ; Define sum-squares?
  (lambda (I N)             ; as a function of two arguments:
    (if                     ;  If
      (add2                 ;   the sum of
        (not-square?        ;    0 if
          (sub2 N I)        ;    N minus I
          1)                ;    is square, < 0 otherwise
                            ;   and
        (not-square? I 1))  ;    0 if I is square, < 0 otherwise
                            ;  is truthy (nonzero), then:
      (if (less? N I)       ;   If N is less than I
        0                   ;   then return 0
        (sum-squares?       ;   Else, recurse with these arguments:
          (add2 I 1)        ;    New I is the next integer
          N))               ;    Same N
      1                     ;  Else (I and N minus I are both square), return 1

Finally, our submission is an anonymous function that takes N only and passes it to sum-squares? with a starting I of 0:

(lambda (N)
  (sum-squares? 0 N))

tinylisp, 125 bytes

(load library
(d V repeat-val
(d R(q((N)(map* *(0to N)(0to N
(q((N)(any(map* contains?(V(map* s(V N(a N 1))(R N))(a N 1))(R N

Try it online!

Octave, 25 bytes

Returns 0 for truthy and 1 for falsy. Quite short considering it's a conventional language.

@(n)0||(k=0:n).^2+k.^2'-n

Try it online!

05AB1E, 8 6 bytes

ÝãnOIå

Bugfixed and -2 bytes thanks to @Mr.Xcoder, making it now similar as @emanresuA's Vyxal answer and @cairdCoinheringaahing's Jelly answer.

Try it online or verify the smaller test cases.

Explanation:

Ý       # Push a list in the range [0, (implicit) input]
 ã      # Create all possible pairs with the cartesian product
  n     # Square each integer
   O    # Sum each inner pair
    Iå  # Check if this list contains the input
        # (after which the result is output implicitly)

Haskell, 41 38 bytes

f n=or[n==x*x+y*y|x<-[0..n],y<-[0..x]]

Try it online!

MATL, 9 8 bytes

0y&:U&+m

Try it online!

(Or this version for larger inputs)

1 for truthy, 0 for falsy. (Thanks to @Giuseppe for -1 byte and this neater output.)

Square every number from 0 upto the input, add all the combinations of them, and check if the input is in there. (The "larger inputs" version does the sensible - but non-golfy - thing of limiting the check upto the square root of the given number; same logic, two extra bytes, a lot less resource hunger.)

Desmos, 52 bytes

a=.5
f(n)=min(ceil(mod((n-[0...floor(n^a)]^2)^a,1)))

Try It On Desmos!

Try It On Desmos! - Prettified

47 bytes (doesn't work past 100 because of Desmos 10000 element restriction)

l=[0...n]
f(n)=min(sign([aa+bb-nfora=l,b=l])^2)

Try It On Desmos!

Try It On Desmos! - Prettified

Excel, 64 bytes

=LET(x,SEQUENCE(SQRT(A1)+1,,1)^2,1-AND(ISERROR(XMATCH(A1-x,x))))

Link to Spreadsheet

List all \$k^2\$ in \$[0..n]\$. Match all \$n - k^2\$ to list. If all matches are errors, then false, otherwise true.

JavaScript (Node.js), 33 bytes

Returns a positive integer for Truthy, and 0 for Falsey.

f=(n,x=1)=>x>n?!n:!(n%x)-f(n,x+2)

Try it online!

This is a trivial modification of @MitchSchwartz's brilliant answer to Count sums of two squares.

Explanation

It can be proven that if \$ n \$ has more \$ 4k + 1 \$ divisors than \$ 4k + 3 \$ divisors, that it can be written as the sum of two squares. One way to achieve this would be to add 1 if n%(4*k+1)==0, and -1 if n%(4*k+3)==0. Writing this down, we can see that the task comes down to computing the following alternating sum:

!(n%1) - !(n%3) + !(n%5) - !(n%7) + ...

which can then be written as:

!(n%1) - (!(n%3) - (!(n%5) - (!(n%7) - ... )))`

The base case of !n handles the special case where n=0, by returning 1 instead.

C (gcc), 88 74 67 66 64 53 bytes

a,b;f(n){for(a=n;~a*n;b=b?--b:--a)n*=a*a+b*b!=n;a=n;}

-14 bytes - thanks to Kevin Cruijssen
-7 bytes - by omitting return (using global variable)
-1 byte - by using - instead of !=
-2 bytes - thanks to AZTECCO
-11 bytes - thanks to AZTECCO x2

Try it online!

Vyxal RM, 5 bytes

Ẋ²Ṡ=a

Try it Online!

Ẋ     # Cartesian product of (implicit range) self with (implicit range) self
 ²    # Square each
  Ṡ   # Sums of each
    a # Do any... 
   =  # Equal the input?

Jelly, 6 bytes

Żpݲ§i

Try it online!

Outputs 0 for falsy, and a non-zero positive integer for truthy. The Footer in the TIO link simply splits the range \$[0, n]\$ into truthy (top line) and falsey (bottom line)

How it works

Żpݲ§i - Main link. Takes n on the left
Ż      - Zero range; [0, 1, ..., n]
  Ż    - Zero range; [0, 1, ..., n]
 p     - Cartesian product
   ²   - Square everything
    §  - Sums of each pair
     i - Index of n, or 0

Python 3, 49 bytes

def f(n):[*{(n-2*x*x)**-2for x in range(n+1)}][n]

Try it online!

Numerics on this and the previous one may be fragile. I don't know whether n**-2 is guaranteed to give the same value as (-n)**-2.

If necessary this can be fixed at the cost of 1 byte.

Old Python 3, 50 bytes

def f(n):[*{(n-2*x*x)**-2 for x in range(n+1)}][n]

Try it online!

Python 3, 53 bytes

def f(n):[*{(n-2*x*x)**2 for x in range(n+1)}-{0}][n]

Try it online!

Old Python 3, 58 bytes

def f(n):[*{sorted({x*x,n-x*x})[1]for x in range(n+1)}][n]

Try it online!

How

Signals by exit code: Errors out for True and returns without error for False. The error is triggered by trying to access list positions which are out of bounds if n is the sum of two squares. In the last two versions the special case a=b triggers a zero division error.

All versions avoid double loops. The first version does it rather clumsily by computing x^2 and n-x^2, taking the maximum and checking for collisions (by counting uniques). The convoluted way of taking the max catches the special case a=b.

The second version implements the same logic a bit smarter: instead of taking the maximum of two values it makes use of he observation that

`n = a^2 + b^2`

can be rewritten

`abs(n-2a^2) = abs(n-2b^2)`

instead of the absolute value we can also take squares. AS before we can check for collisions as long as we do not forget the special case a=b.

The last version takes the reciprocal such that the a=b case triggers a zero division error.

Burlesque, 15 bytes

JqS[GZ2CB)++j~[

Try it online!

Horribly inefficient for falsy, but works

J   # Duplicate input (n)
qS[ # Quoted square
GZ  # Generate squares [0..n)
2CB # All combinations of pairs 
)++ # Sum each pair
j   # Swap stack
~[  # n in list

R, 41 39 bytes

Or R>=4.1, 32 bytes by replacing the word function with a \.

Edit: -2 bytes thanks to @Giuseppe.

function(n)n%in%outer(k<-(0:n)^2,k,`+`)

Try it online!

APL(Dyalog Unicode), 14 bytes SBCS

{⍵∊∘.+⍨×⍨0,⍳⍵}

Try it on APLgolf!

R, 33 bytes

function(n)all((n-(1:n)^2)^.5%%1)

Try it online!

Outputs NA if n is not the sum of 2 squares, FALSE if n is the sum of 2 squares.

If we are restricted to TRUE/FALSE output, then add +4 bytes for 37 bytes, or +3 bytes for 36 bytes if we can reverse the output.

Charcoal, 19 bytes

Nθ≔X…·⁰θ²η⊙η⊙η⁼θ⁺ιλ

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

Nθ

Input n.

≔X…·⁰θ²η

Generate a list of squares from 0 to inclusive (in case n<2).

⊙η⊙η⁼θ⁺ιλ

Check whether any pair sums to n.

Python 3.8 (pre-release), 63 bytes

lambda n:(r:=range(n+1))and n in(i*i+j*j for i in r for j in r)

Try it online!

Ruby, 44 bytes

->n{(k=0..n).any?{|a|k.any?{|b|a*a+b*b==n}}}

Try it online!

Python 3, 59 bytes

lambda n:n in(n and(i//n)**2+(i%n)**2for i in range(n*n+1))

Try it online!

Wolfram Language (Mathematica), 15 bytes

2~SquaresR~#>0&

Try it online!

Brachylog, 7 bytes

~+Ċ~^₂ᵐ

Try it online!

If you put a variable name such as Z as argument, you’ll get the actual couple of values whose squared sum is the input.

Explanation

It’s a direct description of the problem:

~+Ċ        Get a couple of two values Ċ whose sum is the input
  Ċ~^₂ᵐ    Both elements of Ċ must be squares of some numbers