title: The Pedant's Cosine

text:
# Question
Title: The Pedant's Cosine
My boss just told me to write a cosine function. Being a good math geek, my mind immediately conjured the appropriate Taylor Series.

$$\cos(x) = \frac 1 {0!} - \frac {x^2} {2!} + \frac {x^4} {4!} - \frac {x^6} {6!} + \cdots + \frac{(-1)^k \times x^{2k}} {(2k)!} + \cdots$$

However, my boss is very picky. He would like to be able to specify exactly how many terms of the Taylor Series to compute. Can you help me write this function?

### Your Task

Given a floating point value \\$x\\$ from \\$0\\$ to \\$2\pi\\$ and a positive integer \\$n\\$ less than \\$100\\$, compute the sum of the first \\$n\\$ terms of the Taylor series given above for \\$\cos(x)\\$.

This is , so shortest code wins. Input and output can be taken in any of the standard ways. Standard loopholes are forbidden.

### Notes

* Input can be taken in any reasonable form, as long as there is a clear separation between \\$x\\$ and \\$n\\$.
* Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.
* If it makes sense for the language being used, computations may be done using exact rational quantities, but the input and output shall still be in decimal form.

### Examples

```
 x  |  n | Output
----+----+--------------
0.0 |  1 | 1.0
0.5 |  1 | 1.0
0.5 |  2 | 0.875
0.5 |  4 | 0.87758246...
0.5 |  9 | 0.87758256...
2.0 |  2 | -1.0
2.0 |  5 | -0.4158730...

```

# Answer
# Operation Flashpoint scripting language, ~~165~~ 157 bytes

```
F={x=_this select 0;n=_this select 1;i=0;r=0;while{i<n*2}do{r=r+x^i/(i call{c=_this;j=c-1;while{j>0}do{c=c*j;j=j-1};if(c<1)then{c=1};c})*(-1)^(i/2);i=i+2};r}

```

**Call with:**

```
hint format["%1\n%2\n%3\n%4\n%5\n%6\n%7",
    [0.0, 1] call f,
    [0.5, 1] call f,
    [0.5, 2] call f,
    [0.5, 4] call f,
    [0.5, 9] call f,
    [2.0, 2] call f,
    [2.0, 5] call f]

```

**Output:**

> Input and output should be floating-point values, at least as accurate as calculating the formula using single-precision IEEE floating point numbers with some standard rounding rule.

I'm fairly sure that the numbers are single-precision IEEE floating point numbers, even though in the printed output the longer decimals are not that precise. It is the printing that rounds the numbers like that, actually the numbers are more precise.

For instance, `a=1.00001;b=1.000011;hint format["%1\n%2\n%3", a, b, a==b]` will output this:

```
1.00001
1.00001
false

```

So clearly the actual precision of the numbers is greater than the printed precision.
> 67 votes

# Answer
# 05AB1E, ~~14~~ 11 bytes

```
FIn(NmN·!/O

```

Try it online!

**Explanation**

```
F                # for N in [0 ... n] do
 In              # push (x^2)
   (             # negate
    Nm           # raise to the Nth power
      N·!        # push (2*N)!
         /       # divide
          O      # sum

```
> 13 votes

# Answer
# Mathematica, ~~49~~ ~~41~~ ~~39~~ 31 bytes

```
Sum[(-#^2)^k/(2k)!,{k,0,#2-1}]&

```

Old, more "fun" version: (39 bytes)

```
Normal@Series[Cos@k,{k,0,2#2-2}]/.k->#&

```

*Saved 10 bytes thanks to @Pavel and 8 thanks to @Greg Martin!*
> 10 votes

# Answer
# MATL, 14 bytes

```
U_iqE:2ep/YpsQ

```

Try it online! Or verify all test cases.

### Explanation with example

All numbers have double precision (this is the default).

Consider inputs `x = 2.0`, `n = 5`.

```
U_     % Implicitly input x. Square and negate
       % STACK: -4
iqE    % Input n. Subtract 1, multiply by 2
       % STACK: -4, 8
:      % Range
       % STACK: -4, [1 2 3 4 5 6 7 8]
2e     % Reshape into a 2-row matrix
       % STACK: -4, [1 3 5 7;
       %             2 4 6 8]
p      % Product of each column
       % STACK: -4, [2 12 30 56]
/      % Divide, element-wise
       % STACK: [-2 -0.333333333333333 -0.133333333333333 -0.0714285714285714]
Yp     % Cumulative product of array
       % STACK: [-2 0.666666666666667 -0.0888888888888889 0.00634920634920635]
s      % Sum of array
       % STACK: -1.41587301587302
Q      % Add 1. Implicitly display
       % STACK: -0.41587301587302

```
> 10 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
ḶḤµ⁹*÷!_2/S

```

**Try it online!**

### How?

```
ḶḤµ⁹*÷!_2/S - Main link: n, x           e.g. 5, 2.0
Ḷ           - lowered range(n)              [0,1,2,3,4]
 Ḥ          - double (vectorises)           [0,2,4,6,8]
  µ         - monadic chain separation (call that i)
   ⁹        - link's right argument         2.0
    *       - exponentiate(i) (vectorises)  [1.0,4.0,16.0,64.0,256.0]
      !     - factorial(i) (vectorises)     [1,  2,  24,  720, 40320]
     ÷      - divide (vectorises)           [1.0,2.0,0.6666666666666666,0.08888888888888889,0.006349206349206349]
        2/  - pairwise reduce by:
       _    -     subtraction               [-1.0,0.5777777777777777,0.006349206349206349]
         S  - sum                           -0.41587301587301617

```
> 9 votes

# Answer
## **Jelly, 22 bytes**

```
-*ð×ø⁹*⁸²ð÷ø⁸Ḥ!
⁸R’Ç€S

```

This is a full program which takes n as the first argument and x as the second.

Explanation:

```
              Creates a function to compute each term in the series.
Its argument we will call k, eg k=3 computes 3rd term. Take x=2 for example.
-*           Computes (-1)^k. Eg -1
ð×ø        Multiplies by the quantity of
⁹             x.
*             to the power of
⁸             k
²             ...squared. Eg -1 × (2³)²
ð÷ø        divides by the quantity of
⁸              k
Ḥ             doubled
!               ...factorial. Eg -1 × (2³)²/(6!).

                Main link, first argument n and second argument n. Eg n=4, x=2.
⁸R            Creates range(n). Eg [1,2,3,4]
’                Decrements each element. Eg [0,1,2,3]
Ç€            Maps the above function over each element. Eg [1,-2,0.666,-0.0889]
S               Sum all all of the elements.  Eg -0.422.

```
> 8 votes

# Answer
## Python, 54 bytes

```
f=lambda x,n,t=1,p=1:n and t+f(x,n-1,-t*x*x/p/-~p,p+2)

```

If using Python 2, be sure to pass x as a float, not an integer, but I my understanding is that it doesn't matter if you're using Python 3.
> 7 votes

# Answer
# TI-Basic, ~~41~~ 40 bytes

```
Prompt X,N
sum(seq((-(X+1<sub>E</sub>-49)<sup>2</sup>)^Q/((2Q)!),Q,0,N-1

```
`1E-49` is added to the angle because TI-Basic throws an error for 0^0, it's just large enough to not cause the error, and it is not large enough to change the answer.
> 5 votes

# Answer
# , ~~70~~ ~~64~~ 47 bytes

```
function(x,n,m=1:n-1)sum((-x^2)^m/gamma(2*m+1))

```

Try it online!

* uses `gamma(n+1)` instead of `factorial(n)`
* `1:n-1` is equivalent to `0:(n-1)`

Thanks to Dominic van Essen for golfing 17 bytes off by using a basic R feature: vectorization!
> 5 votes

# Answer
## C, 71 bytes

using Horner scheme

```
float f(n,x)float x;{float y;for(n+=n;n;)y=1-(y*x*x/n--)/n--;return y;}

```

Ungolfed version:

```
float f(n,x) float x;
{
  float y = 0.0;
  for(n = 2*n; n>0; n -= 2)
  {
    y = 1-y*x*x/n/(n-1);
  }
  return y;
}

```
> 5 votes

# Answer
## JavaScript (ES6), 46 bytes

```
f=
x=>g=(n,t=1,p=0)=>n&&t+g(--n,-t*x*x/++p/++p,p)
```

```
<div oninput=o.textContent=f(x.value)(n.value)><input id=x><input type=number min=1 value=1 id=n><pre id=o>1
```

Takes curried inputs (x)(n).
> 4 votes

# Answer
# C, 96 bytes

**Recursive** Live

```
f(n){return n?n*f(n-1):1;}float c(n,x)float x;{return n?c(n-1,x)+pow(-1,n)*pow(x,2*n)/f(2*n):1;}

```

**Detailed**

```
f(n) // factorial(n)
{
    return n ?   // n != 0 ?
        n*f(n-1) // n! = n * (n-1)!
    : 1;         // 0! = 1
}

float c(n,x)float x; // cos(x) with n+1 terms
{
    return n ?        // n != 0 ?
        c(n-1, x)     // cos(x) (n-1)th term
        + pow(-1, n)  // + (-1)^n
        * pow(x, 2*n) // * x^(2n)
        / f(2 * n)    // / (2n)!
    : 1;              // cos(x) at n=0
}

```

**Progressive Recursive, 133 bytes** Live

```
#define F float
#define c(x,n) 1+g(1,n,x,1,1,1)
F g(F i,F n,F x,F s,F p,F f){s=-s;p*=x*x;f*=i;return i<n?g(i+1,n,x,s,p,f)+s/2*p/f:0;}

```

**Detailed**

```
#define F float // shorthand float

#define c(x,n) 1+g(1,n,x,1,1,1) // macro function

F g(F i,F n,F x,F s,F p,F f)
{
    s = -s;   // (-1)^n = (-1) * (-1)^(n-1)
    p *= x*x; // x^(2n) =  x^2 * x^(2(n-1))
    f *= i;   //    2n! =    2 * (1*2*..*n)

    return i < n ?       // i = 0 .. n-1
        g(i+1,n,x,s,p,f) // next term
        + s / 2 * p / f  // s*p/2f = s/2*p/f
        : 0;             // don't compute nth term
}

```
> 4 votes

# Answer
# oK, 38 bytes

This also works in **k**, but takes **39 bytes** because one `'` has to be written as `/:` instead (at least, in kmac 2016.06.28 it does).

```
{+/(y#1 -1)*{(*/y#x)%*/1+!y}.'x,'2*!y}

```

Explanation:

Let's start with the middle bit. `(*/y#x)` is exponentiation, it is equivalent to `x^y`. `*/1+!y` would be `y!`, or `y` factorial. `%` is division. Therefore the function in the middle is `middle(x,y) = (x^y)/(y!)`.

Now the bit on the right, to which the function above gets applied. `2*!y` is `{0, 2, 4, ..., 2*(y-1)}`. `x,'` prepends `x` to every item in that list, turning it into `{(x, 0), (x, 2), (x, 4), ..., (x, 2*(y-1))}`. The `.'` then applies `middle` to every pair of numbers (`map`, essentially).

Finally, `(y#1 -1)*` multiplies the result by 1 or -1 (alternating), and `+/` takes the sum.
> 3 votes

# Answer
# Haskell, 71 Bytes

```
f x n=sum$map(\i->(-1)^i*x^(2*i)/fromIntegral(product[1..2*i]))[0..n-1]

```

This is a pretty boring answer that's not too hard to decipher. The `fromIntegral` really bites, though. (The `/` operator requires operands of the same numeric type in Haskell, and coercing between numeric types is not allowed without a wordy function.)
> 3 votes

# Answer
# Jelly, 12 bytes

```
²N*Ḷ}©÷®Ḥ!¤S

```

Try it online!

### How it works

```
²N*Ḷ}©÷®Ḥ!¤S  Main link. Left argument: x. Right argument: n

²             Square; yield x².
 N            Negate; yield -x².
     ©         Call the link to the left and copy the result to the register.
   Ḷ}          Call unlength on the right argument, yielding [0, 1, ..., n-1].
  *           Yield [1, -x², ..., (-x²)**(n-1)].
          ¤   Combine the three links to the left into a niladic chain.
       ®        Yield the value in the register, [0, 1, ..., n-1].
        Ḥ       Unhalve; yield [0, 2, ..., 2n-2].
         !      Factorial; yield [0!, 2!, ..., (2n-2)!].
      ÷         Division; yield [1/0!, -x²/2!, ..., (-x²)**(n-1)/(2n-2)!].
           S  Take the sum.

```
> 3 votes

# Answer
# Haskell, 61 bytes

```
x#n=sum[(-1*x^2)^i/fromIntegral(product[1..2*i])|i<-[0..n-1]]

```

This seemed different enough from the other Haskell solution to warrant a separate answer. Implementation should be pretty self-explanatory—call with `x#n` where `x` is the number the cosine of which is to be computed and `n` is the order of the partial sum to be taken.
> 3 votes

# Answer
# Pyth, 16 bytes

```
sm_Fc^vzyd.!yddU

```

Accepts `n` first, then `x`. Example run.
> 3 votes

# Answer
# Pyt, ~~37~~ ~~34~~ 33 bytes

```
←←ĐĐ↔3Ș1~⇹ř⁻^04Ș⇹ř⁻^²*0↔ř⁻2*!+/+Ʃ

```
> 3 votes

# Answer
# J, ~~26~~ 24 Bytes

```
+/@:(!@]%~^*_1^2%~])2*i.

```

-2 bytes thanks to @cole

I originally planned to use a cyclic gerund to alternate between adding and subtracting, but couldn't get it to work.

### Explanation:

```
                    2*i.     | Integers from 0 to 2(n-1)
    (              )         | Dyadic train:
            _1^-:@]          | -1 to the power of the left argument
          ^*                 | Times left arg to the power of right arg
     !@]%~                   | Divided by the factorial of the right arg
+/@:                         | Sum

```
> 3 votes

# Answer
# Perl 6, 53 bytes

```
{(sum (1,*i*$^x...*)[^2*$^n] »/»(1,|[\*] 1..*)).re}

```

Try it online!

This actually computes the complex exponential *e* for twice the number of requested terms and then takes the real part.
> 3 votes

# Answer
# Julia, 37 bytes

```
x$n=1>(n-=1)||x$n+(-x^2)^n/prod(1:2n)

```

Try it online!
> 3 votes

# Answer
# MATLAB with Symbolic Math Toolbox, 57 bytes

```
@(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))

```

This defines an anonymous function with that takes `double` inputs `x`,`n` and outputs the result as a `double`.

Example (tested on R2015b):

```
>> @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
ans =
    @(x,n)eval(subs(taylor(sym('cos(x)'),'Order',2*n),'x',x))
>> f = ans; format long; f(0,1), f(0.5,1), f(0.5,2), f(0.5,4), f(0.5,9), f(2,2), f(2,5)
ans =
     1
ans =
     1
ans =
   0.875000000000000
ans =
   0.877582465277778
ans =
   0.877582561890373
ans =
    -1
ans =
  -0.415873015873016

```
> 2 votes

# Answer
## C ~~144~~ 130 bytes

```
F(m){int u=1;while(m)u*=m--;return u;}float f(float x,n){float s;for(int i=1;i<n;i++)s+=pow(-1,i)*pow(x,2*i)/(F(2*i));return 1+s;}

```

Ungolfed Version:

```
//Function to calculate factorial
int F(int m)
{
  int u=1;

  while(m>1)
   u*=m--;

  return u;
}

//actual function called in main function
float f(float x, int n)
{

  float s=0.0;

  for(int i=1;i<=n-1;i++)
     s+=pow(-1,i)*pow(x,2*i)/(F(2*i));

  return 1+s;
 }

```

Thanks Kevin for saving some bytes!
> 2 votes

# Answer
# JavaScript ES7 60 bytes

```
x=>a=n=>--n?(-1)**n*x**(2*n)/(f=m=>m?m*f(m-1):1)(2*n)+a(n):1

x=>a=n=>                                                         // Curry-d function, it basically returns another function
        --n?                                              :1  // subtract one from n. If n - 1 is 0, return 1
            (-1)**n*                                             // This generates the sign of the number
                    x**(2*n)/                                    // This creates the part before the division, basicaly x^2n
                             (f=m=>m?m*f(m-1):1)(2*n)            // This creates a recursive factorial function and calls it with 2n
                                                     +a(n)    // Recursively call the function. This adds the elements of the taylor series together

```

To use it:

Press F12, type in the function and then do

```
c(x)(n)

```
> 2 votes

# Answer
# Tcl, 126 bytes

```
proc c {x n k\ 0 r\ 0} {proc F n {expr $n?($n)*\[F $n-1]:1}
time {set r [expr $r+-1**$k*$x**(2*$k)/[F 2*$k]]
incr k} $n
set r}

```

Try it online!
> 2 votes

# Answer
# Stax, 12 bytes

```
ü┘·.ⁿYeò≥Vîû

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
            Input is `x n`
Z           Push a zero underneath the top.  The stack is now `x 0 n`
D           Run the rest of the program n times.
  xJNi|*    (-x*x)^i where i is the iteration index
  iH|F/     divide that by factorial(2i)
  +         add to the running total so far
            final result is implicitly printed

```

Run this one
> 2 votes

# Answer
# Desmos, 36 bytes

```
\sum_{k=0}^{n-1}{(-1)^kv^{2k}/(2k)!}

```

View it on Desmos

Unfortunately, not a ton to golf here.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 30 bytes

```
Normal[Cos@x+O@x^(2#2)]/.x->#&

```

Try it online!

Mathematica has a more (byte-)efficient way to generate `SeriesData` objects than `Series`. `O[x]^p` truncates the power series of the function at the `p`th power.
> 2 votes

# Answer
# Husk, 20 bytes

```
⌊*!9İ⁰ṁ§/ȯΠḣD`^o_□⁰ŀ

```

Try it online!

Outputs sign + 9 decimal places; the initial decimal point is implicit.

14 bytes (`ṁ§/ȯΠḣD`^o_□⁰ŀ`) to calculate the cosine, plus 6 bytes (`⌊*!9İ⁰`) to extract the decimal representation from the a rational number...
> 2 votes

# Answer
# MMIX, 60 bytes (15 instrs)

```
cos SETH $5,#3FF0       // E0053FF0: one = 1.0
    SETL $2,0           // E3020000: twon = 0
    SET  $3,$5          // C1030500: term = one
    FMUL $4,$0,$0       // 10040000: numer = x *. x
    SETL $0,0           // E3000000: accum = 0
    INCH $4,#8000       // E4048000: numer = -.numer
0H  FADD $0,$0,$3       // 04000003: loop: accum +.= term
    FADD $255,$2,$5     // 04FF0205: temp = twon +. 1
    FADD $2,$255,$5     // 0402FF05: twon = temp +. 1
    FMUL $255,$255,$2   // 10FFFF02: temp *.= twon
    FDIV $255,$4,$255   // 14FF04FF: temp = numer /. temp
    FMUL $3,$3,$255     // 100303FF: term *.= temp
    SUBU $1,$1,1        // 27010101: count--
    PBZ  $1,0B          // 5301FFF9: likelyif(!count) goto loop
    POP  1,0            // F8010000: return(accum)

```

This is a really simpleminded algorithm. I managed to avoid using more than three stack temporaries (`$255` is global and free for temporary use, any register numbered less than 32 is guaranteed on-stack).

A few clever tricks and misc notes:
`SET $X,$Y` is a short version of `OR $X,$Y,0`;
it's nice that 1.0 fits entirely in the top quarter of a float, otherwise we would have had to use another instruction to set it;
`PBZ` is a predicted branch (faster if taken) if the register operand is 0;
the `0H` is a local label that the `0B` refers back to; and `POP a,b` means return `a` local variables and skip `b` instructions after the function call.
> 2 votes

# Answer
# PowerShell Core, ~~89~~ 70 bytes

```
param($x,$n)0..--$n|%{$s+="-$x*$x*"*$_+(1..(2*$_)-ne0-join'/')|iex}
$s

```

Try it online!

### Explanation

Generates a string containing each of the member of the sum like

```
-0.5*0.5*-0.5*0.5*0.5*-0.5*0.5*-0.5*1/2/3/4/5/6/7/8

```

Then pass it through `iex` and sums the different iterations.

*-6 bytes thanks to mazzy!*
> 2 votes

# Answer
# JavaScript, 59 bytes

```
x=>k=n=>--n?k(n)+(-1)**n*x**(n*=2)/f(n):1
f=p=>p?p*f(p-1):1

```

Try it online!
> 1 votes

# Answer
# Axiom, 36 bytes

```
g(a,n)==eval(taylor(cos(x)),a).(2*n)

```

Build the infinite (in the meaning finite but one can ask to build the list of 2\*n elements if PC has enough memory) list of partial sums for the Taylor series for cos(x) calculate in 'a', in "eval(taylor(cos(x)),a)"; gets the 2\*n element of that list in ".(2\*n)". Test cases:

```
(47) -> g(0,1)
   (47)  1
                                                 Type: Expression Integer
(48) -> g(0.5,1)
   (48)  1.0
                                                   Type: Expression Float
(49) -> g(0.5,2)
   (49)  0.875
                                                   Type: Expression Float
(50) -> g(0.5,4)
   (50)  0.8775824652 7777777778
                                                   Type: Expression Float
(51) -> g(0.5,9)
   (51)  0.8775825618 9037271611
                                                   Type: Expression Float
(52) -> g(2.0,5)
   (52)  - 0.4158730158 7301587302
                                                   Type: Expression Float
(53) -> g(2.0,800)
   (53)  - 0.4161468365 471423870

```
> 1 votes

# Answer
# PHP, 76 bytes

```
for($f=1;$i<$argv[2]*2;$f*=++$i)$i&1?:$s+=(-1)**$k++*$argv[1]**$i/$f;echo$s;

```

takes `X` and `N` from command line arguments; run with `-r`.

loop `$i` from `0` to `N*2-1`, hold `fac($i)` in `$f`; if `$i` is even, add term to sum`$s`. print sum.

---

I wish I had complex numbers (with `M_I` as imaginary unit);
I would simply multiply `$f` with `M_I*++$i` and save 7 bytes.

Maybe Mathematica can do that. But Mathematica doesn´t have to.

I *could* save two bytes with `cos(M_PI*$i/2)` instead of `$i&1?:` and `(-1)**$k++`;
but it would feel a bit odd to use a cosine builtin to build a cosine function.
> 1 votes

# Answer
# Java, 92 bytes

```
double c(double x,double c,long d,int i){return i>0?r+=c(x,-c/x/x,d/(4*i*i-2*i),--i)+c/d:r;}

```

Try it online!

With comments and whitespaces:

## `C.java`

```
    /*
     * Class 'C' (for 'Cosine').
     * Copyright (C) 2017 Gerold 'Geri' Broser (geribro@users.sourceforge.net)
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
    //package p;

    /** Class 'C' (for Cosine).
     *
     * @author Gerold 'Geri' Broser
     * @version 17.04.21
     * @see https://codegolf.stackexchange.com/questions/116705/the-pedants-cosine
     */
    class C {

        /** The added up results of the polynomial's terms.
         */
        double r;

        /** This one-liner method 'c' (for calculate) returns the part (i=n-1) of a
         *  cosine of a given angle 'x' that's calculated from the second term of a
         *  Taylor series of n polynomial terms onwards (or backwards until the
         *  second term [i=1], to be precise, see below).
         *
         *  It achieves this by doing the following:
         *
         * ● It doesn't calculate the first term since it is always 1 anyway.
         *
         * ● It uses recursion for calculating the terms of the polynomial.
         *
         * ● It calculates from the rightmost term back to the leftmost. Such avoiding
         *   to keep the upper boundary stored till the end for the recursion's stop
         *   condition.
         *
         * ● It is supplied with values for the counter and denominator of the
         *   rightmost term at invocation. Such also the user can decide which
         *   library to take for power and factorial.
         *
         * ● It calculates the counters and denominators for each term from scratch
         *   at each recursion but uses the values calculated at the previous
         *   recursion. Such the new values can be calculated by using trivial
         *   parenthesis, division, multiplication, decrement and negation only.
         *   This doesn't only save characters but probably is also faster than
         *   power and factorial.
         *   [It could be made be even faster for x=2^n, n ∈ N, because we can
         *   use the unsigned right shift operator '>>>' instead of divisions then
         *   (see method 'calculateForXisPowerOfTwo()' of class 'Cosine').]
         *
         * @param x angle (independent variable) in radians
         * @param c counter of last term specified by index 'i' including proper sign
         *          (see class 'CTest')
         * @param d denominator of last term specified by index 'i' (see class 'CTest')
         * @param i index of last term used in the calculation (=number of terms 'n'
         *          minus 1; Σ's upper boundary)
         *
         * @see https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions
         */

        // Copy the following three lines to immediately after the function header for testing:
        //  System.out.printf(
        //          "c(): x:%4.1f  c:%24.17f  d:%,19d  i:%2d  t:%40.35f%n",
        //          x, c, d, i, c / d);

        // Position of 'i' is relevant here, since it is prefix-decremented inline!
        double c( double x, double c, long d, int i ) {
            return i > 0
                    ? r += c(
                        x,
                        -c / x / x,
                        d / (4 * i * i - 2 * i),
                        --i )
                        + c / d
                    : r;
        } // c()
    } // C

```

## `CTest.java`

```
    /*
     * Class 'CTest' (for 'Cosine Test').
     * Copyright (C) 2017 Gerold 'Geri' Broser (geribro@users.sourceforge.net)
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     */
    package p;

    import org.apache.commons.math3.util.CombinatoricsUtils;

    /** Test class for methods 'c' (for calculate) of class 'C' (for Cosine).
     *
     * @author Gerold 'Geri' Broser
     * @version 17.04.21
     * @see https://codegolf.stackexchange.com/questions/116705/the-pedants-cosine
     */
    public class CTest {

        /** The Unicode character 'ₛ' is the subscript character for 's'. It stands for the plural 's'
         *  in the array's names. ('xs' wasn't matching my BMI. 'ns' looked like a system that we have
         *  overcome since decades and like the German abbreviation for...I'm leaving that one out now.)
         *
         * @param args command line arguments
         */
        public static void main( String[] args ) {

            double[] xₛ = { .0, .5, .5, .5, .5, 2., 2. };
            int[] nₛ = { 1, 1, 2, 4, 9, 2, 5 };

            System.out.println(
                    "┌────┬─────┬───┬───────────────────────┐\n" +
                    "│ No │  x  │ n │        cos(x)         │\n" +
                    "├────┤─────┼───┼───────────────────────┤" );
            for ( int i = 0; i < xₛ.length; i++ ) {

                System.out.printf( "│ %d. │ %2.1f │ %d │ %,21.18f │%n",
                        i + 1,
                        xₛ[i], // x (angle)
                        nₛ[i]--, // n (number of terms of the polynomial, decreased for further processing as index)
                        1.0 + new C().c(
                                xₛ[i], // x (angle in radians)
                                Math.pow( -1, nₛ[i] ) // negate alternating starting with minus for the second term
                                        * Math.pow( xₛ[i], 2 * nₛ[i] ), // counter for the rightmost term (c)
                                CombinatoricsUtils.factorial( 2 * nₛ[i] ), // denominator for the rightmost term (d)
                                nₛ[i] // index of last term of the polynomial
                        ) );

            } // for ( C test case )
            System.out.println( "└────┴─────┴───┴───────────────────────┘" );
        } // main()
    } // CTest

```

## Output

```
┌────┬─────┬───┬───────────────────────┐
│ No │  x  │ n │        cos(x)         │
├────┤─────┼───┼───────────────────────┤
│ 1. │ 0,0 │ 1 │  1,000000000000000000 │
│ 2. │ 0,5 │ 1 │  1,000000000000000000 │
│ 3. │ 0,5 │ 2 │  0,875000000000000000 │
│ 4. │ 0,5 │ 4 │  0,877582465277777700 │
│ 5. │ 0,5 │ 9 │  0,877582561890372800 │
│ 6. │ 2,0 │ 2 │ -1,000000000000000000 │
│ 7. │ 2,0 │ 5 │ -0,415873015873015950 │
└────┴─────┴───┴───────────────────────┘

```
> 1 votes

# Answer
# , 17 bytes

```
4 :'2&o.T.(+:y)x'

```

Try it online!

Uses a built-in, which I assume is OK.

Unfortunately, I don't really know how to work well with functions that take arguments via currying like this, so I had to do this explicitly. I'm sure that there is a way to do it tacitly or shorter.
> 1 votes

# Answer
# Clean, 77 bytes

```
import StdEnv
?x n=sum[(-1.0)^(p/2.0)*x^p/prod[1.0..p]\\p<-take n[0.0,2.0..]]

```

Try it online!
> 1 votes

# Answer
# Pari/GP, 35 bytes

```
f(x,n)=sum(i=0,n-1,(-x^2)^i/(2*i)!)

```

Try it online!
> 1 votes

# Answer
## F#, ~~177~~ 146 bytes

```
let rec f x=if x<2 then 1 else f(x-1)*x
let i n x=(pown -1.0 n)*(pown x (2*n))/float(f(2*n))
let t x k=seq{for j=0 to(k-1)do yield i j x}|>Seq.sum

```

Try it online!

Shaved off 31 bytes thanks to Emmanuel showing me operators in F# that I wasn't aware of. I had a look at `Microsoft.FSharp.Core.Operators` and found some useful stuff there. Thanks a million!

`f` is a recursive factorial function. `i` is one item in the series, and `t` is the actual Taylor Series itself - iterate through from `0` to `k-1`, evaluating `i` at each stage, and sum the results.
> 1 votes

# Answer
# PowerShell Core, ~~59~~ 56 bytes

*-3 bytes thanks to Julian*

```
param($x,$n)$v=1
1..$n|%{$s+=$v;$v*=-$x*$x/++$k/++$k}
$s

```

Try it online!
> 1 votes

# Answer
# APL(NARS), 64 chars

```
r←p C w;d;v;m
r←d←1⋄m←w×w×¯1⋄v←¯1,0
→0×⍳0≥p-←1⋄r+←d×←m÷×/v+←2⋄→2

```

13+21+28+2=64

How to use and test:

```
  {⍵,⍵ C 0.5} ¨ 0..5
┌6─────────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───────┐ ┌2──────────────┐ ┌2──────────────┐ ┌2──────────────┐│
││ 0 1│ │ 1 1│ │ 2 0.875│ │ 3 0.8776041667│ │ 4 0.8775824653│ │ 5 0.8775825622││
│└~───┘ └~───┘ └~───────┘ └~──────────────┘ └~──────────────┘ └~──────────────┘2
└∊─────────────────────────────────────────────────────────────────────────────┘

```

OT these below should be the answers 100% precise but not in decimal

```
  {⍵,⍵ C 1r2} ¨ 0..5
┌6─────────────────────────────────────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2─────┐ ┌2─────────┐ ┌2─────────────┐ ┌2──────────────────┐│
││ 0 1│ │ 1 1│ │ 2 7r8│ │ 3 337r384│ │ 4 40439r46080│ │ 5 9058337r10321920││
│└~───┘ └~───┘ └~─────┘ └~─────────┘ └~─────────────┘ └~──────────────────┘2
└∊─────────────────────────────────────────────────────────────────────────┘

```

7r8 means 7/8 .
> 1 votes

# Answer
# Vyxal , 8 bytes

```
ʁd~e$¡/∑

```

Try it Online! The  flag is to output as a decimal.

```
ʁ        # Range from 0 to n-1
 d       # doubled
  ~e     # x ** each of that
      /  # Divided by
    $¡   # Factorial of each of that
       ∑ # Sum

```
> 1 votes

# Answer
# C (tcc), 103 bytes

```
double r,d,m,co(int n,double w){int x=-1,y=0;for(r=d=1,m=-w*w;--n>0;x+=2,y+=2,r+=d*=m/(x*y));return r;}

```

Try it online!
> 1 votes

---
Tags: code-golf, math, trigonometry, calculus
---


title: Nth term of Van Eck Sequence

text:
# Question
Title: Nth term of Van Eck Sequence
Output the Nth term of the Van Eck Sequence.

Van Eck Sequence is defined as:

* Starts with 0.
* If the last term is the first occurrence of that term the next term is 0.
* If the last term has occurred previously the next term is how many steps back was the most recent occurrence.

https://oeis.org/A181391

https://www.youtube.com/watch?v=etMJxB-igrc

https://www.youtube.com/watch?v=8VrnqRU7BVU

Sequence: 0,0,1,0,2,0,2,2,1,6,0,5,0,2,...

Tests:

Input | Output

* 1 | 0
* 8 | 2
* 19 | 5
* 27 | 9
* 52 | 42
* 64 | 0

**EDIT**

1 indexed is preferred, 0 indexed is acceptable; that might change some of the already submitted solutions.

Just the Nth term please.

Same (except for the seeing it already posted part), it seems code golfers and numberphile watchers have a decent overlap.

# Answer
# JavaScript (ES6),  ~~46 41~~  37 bytes

```
n=>(g=p=>--n?g(g[p]-n|0,g[p]=n):p)(0)

```

Try it online!

### How?

We don't need to store the full sequence. We only need to keep track of the last position of each integer that appears in the sequence. We use the underlying object of the recursive function \\$g\\$ for that purpose.

For a given term \\$p\\$, we don't need either to set \\$g\[p\]\\$ to its actual absolute position in the sequence because we're only interested in the distance with the current position. That's why we can just store the current value of the input \\$n\\$, which is used as a decrementing counter in the code.

Therefore, the distance is given by \\$g\[p\]-n\\$. Conveniently, this evaluates to *NaN* if this is the first occurrence of \\$p\\$, which can be easily turned into the expected \\$0\\$.

### Commented

```
n => (           // n = input
  g = p =>       // g = recursive function taking p = previous term of the
                 //     sequence; g is also used as an object to store the
                 //     last position of each integer found in the sequence
    --n ?        // decrement n; if it's not equal to 0:
      g(         //   do a recursive call:
        g[p] - n //     subtract n from the last position of p
                 //     if g[p] is undefined, the above expression evaluates
        | 0,     //     to NaN, in which case we coerce it to 0 instead
        g[p] = n //     update g[p] to n
      )          //   end of recursive call
    :            // else:
      p          //   we've reached the requested term:
                 //   stop the recursion and return it
)(0)             // initial call to g with p = 0

```
> 28 votes

# Answer
# Python 3, ~~69~~ ~~63~~ 62 bytes

```
f=lambda n,l=0,*s:f(n-1,l in s and~s.index(l),l,*s)if n else-l

```

Try it online!

 Note: as Erik the Outgolfer mentioned, this code works fine in Python 2 as well.

0-indexed (although, just to be utterly perverse, you can make it -1-indexed by changing `if n` to `if~n` :P)

Makes use of Python's gorgeous unpacking "star operator", to recursively build up the series, until `n` reaches zero.

The function builds up the series in the reverse order, to avoid having to reverse it for the search. Additionally, it actually stores the negations of all the elements, because converting them back at the end was free (else the `-` would have had to be a space) and it saves us a byte along the way, by using `~s.index(l)` instead of `-~s.index(l)`.

Could be 51 bytes if Python tuples had the same `find` functions strings do (returning -1 if not found, instead of raising an error), but no such luck...
> 21 votes

# Answer
# , 62 bytes

```
function(n){while(sum(F|1)<n)F=c(match(F[1],F[-1],0),F)
+F[1]}

```

Try it online!

Builds the list in reverse; `match` returns the *first* index of `F[1]` (the previous value) in `F[-1]` (the remainder of the list), returning `0` if no match is found.

`F` is initialized to `FALSE` and is coerced to `0` on the first pass of the `while` loop.
> 10 votes

# Answer
# Perl 6, ~~47~~ 42 bytes

*-5 bytes thanks to nwellnhof*

```
{({+grep(@_[*-1],:k,[R,] @_)[1]}...*)[$_]}

```

Try it online!

Anonymous codeblock that outputs the 0-indexed element in the sequence.

### Explanation:

```
{                                            } # Anonymous codeblock
 (                                      )[$_]  # Return the nth element
                                    ...*       # Of the infinite sequence
  {                            }  # Where each element is
    grep(        :k        )[1]   # The key of the second occurrence
         @_[*-1],                 # Of the most recent element
                   ,[R,] @_       # In the reversed sequence so far
   +     # And numify the Nil to 0 if the element is not found

```
> 10 votes

# Answer
# Bourne shell, 102 bytes

```
until [ 0"$i" -eq $1 ];do i=$((${i:-0}+1)) a=${n:-0};eval 'n=$(($i-${m'$a:-$i'}))' m$a=$i;done;echo $a

```

try it online
> 8 votes

# Answer
# Python, 51 bytes

```
f=lambda n,i=1:n>i and[f(n,i+1),i][f(n-1)==f(n+~i)]

```

Try it online!

Outputs `False` for `0`. Implements the spec pretty literally, looking for the lowest positive integer `i` such that `f(n-1)==f(n-i-1)`. If such a search leads to `i>=n`, the previous element hasn't appeared before and we produce `0`.

Instead of doing something reasonable like storing earlier values in a list, the function just recomputes them recursively from scratch whenever they're needed, and sometimes when they're not needed. This makes the function run very slowly for inputs above 10 or so.
> 8 votes

# Answer
# , ~~29~~ 23 bytes

```
1{(,~#|1+}.i.{.)@]^:[&0

```

Try it online!

The real work is done in the iteration verb of the power verb `^:`, which iterates as many times as the argument `[`, starting the iteration with the constant value 0 `&0`...

* `(#|1+}.i.{.)` This is what iterates. Breaking it down...
* `}.i.{.` Find the index of `i.` of the head of the list `{.` within the tail of the list `}.`. This will return a 0-based index, so if the current item is found 1 previous it will return 0. If it is not found, it will return the length of the list, ie, the length of the tail.
* `1+` Add one to the value to correct for the 0-based indexing, since the Ven Eck's "how far back" is 1-based. Note that if it was not found, the value will now be the length of the full list.
* `#|` Return the remainder of the value calculated in the previous step, when divided by the length of the full list. Note that this turns "not found" into 0, but leaves all other values unchanged.
* `,~` Append the new value to the front of the list. We use the front rather than last merely for convenience.
* `1{` return the 2nd item in the list, since we calculated one too many times because it's shorter that way.
> 7 votes

# Answer
# Stax, ~~10~~ 9 bytes

```
é"▬π²"ô↕j

```

Run and debug it

If 0-based indexing is allowed:

### Stax, 8 bytes

```
à┐æ8Å/[┤

```

Run and debug it
> 6 votes

# Answer
# Wolfram Language (Mathematica), 48 bytes

```
#<1||Last[#-1-Array[#0,#-2]~Position~#0[#-1],0]&

```

Try it online!

Nonzero values are returned as singleton lists.
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~19~~ 17 bytesSBCS

Many thanks to ngn, Adám, Richard Park and H.PWiz for their help in writing and golfing this answer in The APL Orchard, a great place to learn APL and get APL help.

**Edit:** -2 bytes from Adám.

```
⊃(⊢,⍨≢|1∘↓⍳⊃)⍣⎕-1

```

Try it online!

**Explanation**

```
⊃(⊢,⍨≢|1∘↓⍳⊃)⍣⎕-1

                 -1  We initialize our array of results with -1.
 (           )⍣⎕    ⍣ repeats the train (in parentheses) our input, ⎕, times.
        1∘↓⍳⊃        We take the index of the head (our last element in the sequence).
                     To signify "element not found", this returns the length of the array.
      ≢|             We take our index modulo the length of the array.
                     This turns our "element not found" from the length of the array to 0.
  ⊢,⍨                And we prepend to our array.
⊃                    Finally, we return the first element of the array,
                     which is the most recently-generated.
                     This is the ⍵-th element of the Van Eck sequence.

```
> 5 votes

# Answer
# 05AB1E, 8 bytes

```
F¯Rćk>Dˆ

```

Try it online or output the first \\$n\\$ values in the list.

**Explanation:**

```
F         # Loop the (implicit) input amount of times:
 ¯        #  Push the global array
  R       #  Reverse it
   ć      #  Extract the head; push the remainder and the head to the stack
    k     #  Get the 0-based index of the head in the remainder (-1 if not found)
     >    #  Increase it by 1 to make it 1-indexed (or 0 if not found)
      Dˆ  #  Add a copy to the global array
          # (after the loop, output the top of the stack implicitly as result,
          #  which is why we need the `D`/duplicate)

```
> 4 votes

# Answer
## Java, 96 80 76 bytes

```
n->{int i,v=0,m[]=new int[n];for(;--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;}

```

Not obfuscated:

```
Function<Integer, Integer> vanEck =
n -> {

    int i;                  // i is the value of n when v was previously encountered
    int v = 0;              // v is the current element of vanEck sequence
    int[] m = new int[n];   // m[v] is the value of n when v was previously encountered

    while (--n > 0) {       // n is used as a decrementing counter

        i = m[v];
        m[v] = n;
        v = i == 0 ? 0 : i - n;
    }

    return v;
};

```
> 4 votes

# Answer
# Jelly, 7 bytes

```
Ḷß€ṚiḢ$

```

Try it online!

0-indexed.
> 3 votes

# Answer
# Charcoal, 23 bytes

```
≔⁰θＦ⊖Ｎ«≔⊕⌕⮌υθη⊞υθ≔ηθ»Ｉθ

```

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

```
≔⁰θ

```

Set the first term to 0.

```
Ｆ⊖Ｎ«

```

Loop `n-1` times. (If 0-indexing is acceptable, the  can be removed for a 1-byte saving.)

```
≔⊕⌕⮌υθη

```

The next term is the incremented index of the current term in the reversed list of previous terms.

```
⊞υθ

```

Add the current term to the list of previous terms.

```
≔ηθ

```

Set the current term to the next term.

```
»Ｉθ

```

Print the current term at the end of the loop.
> 3 votes

# Answer
# Perl 5 (`-p`), 42 bytes

```
map{($\,$\{$\})=0|$\{$\};$_++for%\}1..$_}{

```

Try it online!
> 3 votes

# Answer
# Husk, ~~8~~ 7 bytes

```
!¡oΓ€↔ø

```

Try it online! The behavior of  is surprisingly helpful here.
> 3 votes

# Answer
# Haskell, 42 bytes

```
f n=last$0:[n-j-1|j<-[0..n-2],f j==f(n-1)]

```

Try it online!

Other Haskell answers: 66 bytes by flawr and 61 bytes by nimi.
> 3 votes

# Answer
# Jelly, 8 bytes

```
ẎiḢ$;µ¡Ḣ

```

A monadic Link accepting a positive integer, \\$n\\$, which yields the \\$n^{th}\\$ term of the Van Eck Sequence.

**Try it online!**

### How?

```
ẎiḢ$;µ¡Ḣ - Link: n
     µ¡  - repeat this monadic link n times - i.e. f(f(...f(n)...)):
         - (call the current argument L)
Ẏ        -   tighten (ensures we have a copy of L, so that Ḣ doesn't alter it)
   $     -   last two links as a monad:
  Ḣ      -     head (pop off & yield leftmost of the copy)
 i       -     first index (of that in the rest) or 0 if not found
    ;    -   concatenate with L
       Ḣ - head

```

Note that without the final  we've actually collected `[a(n), a(n-1), ..., a(2), a(1), n]`
> 2 votes

# Answer
# C (gcc), 63 bytes

```
f(n){n=g(n,--n);}g(n,i){n=n>0?f(--n)-f(i)?g(n,i)+!!g(n,i):1:0;}

```

Try it online!

0-indexed.
> 2 votes

# Answer
# Haskell, ~~68 67~~ 66 bytes

Quite straightforward implementation (using 0 based indexing).

```
f n|all((/=f(n-1)).f)[0..n-2]=0|m<-n-1=[k|k<-[1..],f(m-k)==f m]!!0

```

Try it online!
> 2 votes

# Answer
## Haskell, 61 bytes

```
(([]#0)1!!)
(l#n)i=n:(((n,i):l)#maybe 0(i-)(lookup n l))(i+1)

```

0-based indexing.

Try it online!
> 2 votes

# Answer
# Japt `-h`, 11 bytes

```
@ÒZÔÅbX}hTo

```

Try it
> 2 votes

# Answer
## CJam (15 bytes)

```
0a{_(#)\+}qi*0=

```

Online demo. This is a full program and 0-indexed.

### Dissection

```
0a      e# Push the array [0]
{       e# Loop...
  _(#   e#   Copy the array, pop the first element, and find its index in the array
  )\+   e#   Increment and prepend
}qi*    e# ... n times, where n is read from stdin
0=      e# Take the first element of the array

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 77 bytes

```
n=>{int i,v=0;for(var m=new int[n];--n>0;m[v]=n,v=i<1?0:i-n)i=m[v];return v;}

```

Try it online!

Pretty much a port of the Java answer at this point.
> 2 votes

# Answer
# Python 3, ~~128~~ ~~114~~ ~~111~~ ~~102~~ 99 bytes

*102 -\> 99 bytes, thanks to Jonathan Frech*

```
f=lambda n,i=1,l=[0]:f(n,i+1,l+[l[i-2::-1].index(l[-1])+1if l[-1]in l[:-1]else 0])if n>i else l[-1]

```

Try it online!
> 2 votes

# Answer
# Vyxal, 8 bytes

```
W?(p:ḣḟ›

```

Try it Online! 1-indexed.

**Explanation:**

Since \\$a(n) \< n\\$, we can push \\$n\\$ to the beginning of the list. Also builds the sequence backwards.

```
W?(p:ḣḟ› # whole program

W        # []
 ?       #            input
  (      # repeat for       times:
   p     #  prepend to list (uses implicit input the first time)
    :    #  duplicate
     ḣ   #  split head from the rest
      ḟ  #  find its index on the list (-1 if none)
       › #  increment
         # as we didn't prepend the last item, output it

```
> 2 votes

# Answer
# Python 3, 112 bytes

```
a=[0]
for _ in a*int(input()):k=a[-1];a+=k in a[:-1]and[a[::-1].index(k)+~a[-2::-1].index(k)]or[0]
print(-a[-2])

```

Try it online!

-3 bytes thanks to mypetlion
> 1 votes

# Answer
# Red, ~~106~~ 95 bytes

```
func[n][b: copy[0]loop n[insert b either not find t: next b
b/1[0][-1 + index? find t b/1]]b/2]

```

Try it online!
> 1 votes

# Answer
# Pyth, 18 bytes

```
VQ=Y+?YhxtYhY0Y;hY

```

Try it online!

Builds up the sequence in reverse and prints the first element (last term of the sequence).

```
VQ                 # for N in range(Q) (Q=input)
  =Y+         Y    # Y.prepend(
        xtY        #   Y[1:].index(    )
           hY      #               Y[0]
       h           #                     +1
     ?Y      0     #                        if Y else 0)
               ;hY # end for loop and print Y[0]

```
> 1 votes

# Answer
# Arn `-f`, 13 bytes

```
f→S›J⁻åƒƒN5═%

```

Try it! 0-indexed

# Explained

Unpacked: `&.{++.{:i:{)|}[`

```
&.            Mutate S N times
  {             With block, key of `_`
      ++        Increment
            _   Implicit
          .{    Behead
        :i      Index of
            _   Implicit
          :{    Head
      )     Don't ask
    |           Concatenated with
      _         Implicit
  }             End block
  [           Where S is an array
  ]             Ending implicit
  _           And N is STDIN; implicit
            Then take the head

```
> 1 votes

# Answer
# Nibbles, 5.5 bytes (11 nibbles)

```
=$.~~0?`)$

```

```
=$           # get the input-th element of:
  .~~        #   append until null (=for ever)
     0       #   starting with 0
      ?      #     get the index (or 0 if absent)
       `)$   #     in the list-so-far without its first element
             #     of its first element

```

I expected to need to reverse (`\`) the list-so-far (so: `=$.~~0?`)\$` for 6 bytes), but somehow this works without doing that. I'm not sure why.
> 1 votes

# Answer
# Uiua 0.10.0, 17 bytes SBCS

```
⊢⍥(⊂⬚0⊡1⊚⌕⊢..):¤0

```

Try on Uiua Pad! Constructs the sequence in reverse order and then just takes the first entry. Golfed from a solution by @5imon in the Uiua Discord
> 1 votes

# Answer
## Clojure, 69 bytes

```
#((fn f[i c t](if(= i 1)t(f(dec i)(assoc c t i)(-(or(c t)i)i))))%{}0)

```

Sadly a more functional approach seems to be longer.
> 0 votes

# Answer
# C++ (clang), ~~241~~ ~~235~~ ~~234~~ ~~219~~ ~~197~~ 189 bytes

*197 -\> 189 bytes, thanks to ceilingcat*

```
#import<bits/stdc++.h>
int f(int n,int i=0,std::vector<int>l={0}){return~-n>i?l.push_back(find(begin(l),end(l)-1,l[i])-end(l)+1?find(rbegin(l)+1,rend(l),l[i])-rbegin(l):0),f(n,i+1,l):l[i];}

```

Try it online!
> 0 votes

# Answer
# **DC, 94 91 90 bytes**

Input is taken during the program. Save this to a file and then do "dc " to run. Definitely not the shortest, but I have fun with challenges like these in dc. Input is 1-based index, as preferred.

[st1si0swlbxltlwlu1-sulu0!=m]sm[dlt=qSsli1+siz0!=b0siLs]sb[0pq]sf[lisw2Q]sq?2-dsu1>f0dlmxp

Main control macro
[st                         ]sm   save top value as target
[  1si0sw                   ]sm   reset i to 1 and w to 0
[        lbx                ]sm   execute macro b to get next value in w
[           ltlw            ]sm   restore target to the stack and add w to the stack
[               lu1-su      ]sm   decrement the user inputted variable
[                     lu0!=m]sm   if the user inputted variable is not 0 recurse

Next value finder macro
[dlt=q                  ]sb     if the value on the stack is the target, quit
[     Ss                ]sb     save top value to s register
[       li1+si          ]sb     increment i register
[             z0!=b     ]sb     recurse if still more values
[                  0si  ]sb     set i to 0 (will be saved to w if relevant)
[                     Ls]sb     move top value of s register to stack

[lisw2Q]sq   Load i, save it to w, and then quit this macro and the one that called it

[0pq]sf print 0 and quit the program
```

> 0 votes

---
Tags: code-golf, sequence
---


title: It's Hip to be Square

text:
# Question
Title: It's Hip to be Square
# Challenge

So, um, it seems that, while we have plenty of challenges that work with square numbers or numbers of other shapes, we don't have one that simply asks:

Given an integer `n` (where `n>=0`) as input return a truthy value if `n` is a perfect square or a falsey value if not.

---

## Rules

* You may take input by any reasonable, convenient means as long as it's permitted by standard I/O rules.
* You need not handle inputs greater than what your chosen language can natively handle nor which would lead to floating point inaccuracies.
* Output should be one of two consistent truthy/falsey values (e.g., `true` or `false`, `1` or `0`) - truthy if the input is a perfect square, falsey if it's not.
* This is so lowest byte count wins.

---

## Test Cases

```
Input:  0
Output: true

Input:  1
Output: true

Input:  64
Output: true

Input:  88
Output: false

Input:  2147483647
Output: false

```

# Answer
> 29 votes
# Neim, 2 bytes

```
q

```

Explanation:

```
q      Push an infinite list of squares
      Is the input in that list?

```

When I say 'infinite' I mean up until we hit the maximum value of longs (2^63-1). However, Neim is (slowly) transitioning to theoretically infinitely large BigIntegers.

Try it!

# Answer
> 10 votes
# Jelly, 2 bytes

```
Æ²

```

Try it online!

# Answer
> 9 votes
# dc, 9

```
0?dvd*-^p

```

Outputs 1 for truthy and 0 for falsey.

Try it online.

```
0            # Push zero.  Stack: [ 0 ]
 ?           # Push input.  Stack: [ n, 0 ]
  dv         # duplicate and take integer square root.  Stack: [ ⌊√n⌋, n, 0 ]
    d        # duplicate.  Stack: [ ⌊√n⌋, ⌊√n⌋, n, 0 ]
     *       # multiply.  Stack: [ ⌊√n⌋², n, 0 ]
      -      # take difference. Stack: [ n-⌊√n⌋², 0 ]
       ^     # 0 to power of the result.  Stack: [ 0^(n-⌊√n⌋²) ]
        p    # print.

```

Note `dc`'s `^` exponentiation command gives 00=1 and 0n=0, where n\>0.

# Answer
> 8 votes
# C#, 27 bytes

```
n=>System.Math.Sqrt(n)%1==0

```

---

A more correct/accurate way to do this would be:

```
n=>System.Math.Sqrt(n)%1<=double.Epsilon*100

```

# Answer
> 8 votes
# TI-Basic, 4 bytes

```
not(fPart(√(Ans

```

Simply checks if the square root is an integer by looking for a nonzero fractional/decimal part.

# Answer
> 8 votes
# JavaScript (ES6), 13 bytes

```
n=>!(n**.5%1)

```

Returns true if the square root of n is a whole number.

**Snippet:**

```
f=
n=>!(n**.5%1)

console.log(f(0));
console.log(f(1));
console.log(f(2));
console.log(f(4));
console.log(f(8));
console.log(f(16));
console.log(f(88));
console.log(f(2147483647));
```

# Answer
> 6 votes
# Retina, 18 bytes

```
.+
$*
(^1?|11\1)+$

```

Try it online! Shamelessly adapted from @MartinEnder's answer to Is this number triangular? but with the base conversion included at a cost of 6 bytes.

Note that Is this number triangular? wasn't for some inexplicable reason required to support zero as a triangular number, so part of the adaption was to add a `?` to make the leading 1 optional, allowing the group to match the empty string, and therefore a zero input. However, having now matched the empty string, the `+` operator stops repeating, to avoid the infinite loop that would happen if it kept greedily matching the empty string (after all, `^1?` would certainly keep matching). This means that it doesn't even try to match the other alternative in the group, thus avoiding the match of 2, 6, 12 etc. As @MartinEnder points out, a simpler way to avoid that while still matching the empty string is to anchor the match at the start while making the group optional for the same byte count: `^(^1|11\1)*$`.

# Answer
> 6 votes
# Perl 5, 14 bytes

13 bytes of code + `-p` flag.

```
$_=sqrt!~/\./

```

Try it online!

Computes the square root, and looks if it's an integer (more precisely, if it doesn't contain a dot (`/\./`).

# Answer
> 6 votes
# Python 3, 19 bytes

```
lambda n:n**.5%1==0

```

Try it online!

# Answer
> 6 votes
# MATL, ~~5~~ 4 bytes

Thanks to Luis for reducing my one byte longer code by two bytes, making it the shortest one.

```
t:Um

```

Try it online

**Explanation:**

```
         % Implicit input
t        % Duplicate it
 :       % Range from 1 to input value
  U      % Square the range, to get 1 4 9 ...
   m     % ismember, Checks if the input is a member of the range of perfect squares

```

---

Old answer:

```
X^1\~

```

Try it online!

```
        % Implicit input
X^      % Square root of input
  1\    % Modulus 1. All perfect squares will have 0, the rest will have decimal value
     ~  % Negate, so the 0 becomes 1, and the decimal values become 0

```

# Answer
> 6 votes
# C (gcc), 30 bytes

```
f(n){n=sqrt(n)==(int)sqrt(n);}

```

Try it online!

# C, 34 bytes

```
f(n){return(int)sqrt(n)==sqrt(n);}

```

Try it online!

# C, 33 bytes

```
#define f(n)(int)sqrt(n)==sqrt(n)

```

Try it online!

# Answer
> 6 votes
# Python 3, ~~40~~ 38 bytes

*Thanks to squid for saving 2 bytes!*

```
lambda n:n in(i*i for i in range(n+1))

```

Try it online!

Too slow to return an answer for `2147483647` in a reasonable amount of time. (But written using a generator to save memory, since it doesn't cost any bytes.)

Works in Python 2 also, though an `OverflowError` is a possibility due to `range` if you try it with huge inputs. (A `MemoryError` would also be likely in Python 2, also due to `range`.)

# Answer
> 6 votes
# MathGolf, 1 byte

```
°

```

Try it online!

I don't think an explanation is needed. I saw the need for an "is perfect square" operator before I saw this challenge, as the language is designed to handle math related golf challenges. Returns 0 or 1, as MathGolf uses integers to represent booleans.

# Answer
> 6 votes
# Regex (ECMAScript / Python or better), 50 bytes

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

```

Try it online!

This regex is explained in Match strings whose length is a fourth power. teukon and I arrived at it independently, starting on 2014-02-22, though golfing it down to this point took him 2 days and took me 4 days. It works by dividing away squared prime factors one at a time, thus keeping the number's property of being a square at every step iff it started out being a square. This regex represents a local minimum in length; it's the shortest form that this particular algorithm can be golfed into. It can be modified to match Nth powers by changing the `2` in `{2}` to N.

# Regex (ECMAScript), 28 bytes

```
^(x(x*)|)(?=(\1*)\2+$)\1*$\3

```

Try it online!

```
^              # tail = C = input number
(x(x*)|)       # \1 = A = conjectured square root of C; \2 = A-1, or unset if A==0,
               # allowing us to match C==0 using ECMAScript NPCG behavior; tail -= A
(?=
    (\1*)\2+$  # iff A*A==C, the first match here must result in \3==0
)
\1*$\3         # assert A divides tail, and \3==0

```

This ultimate form of this was arrived upon from 2014-03-02 to 2014-03-04 through several rounds of golfing between teukon and me, after we had already independently come up with the coprime moduli method of generalized multiplication (which took him 3 hours and took me almost 2 days). I came up with the idea to do one of the tests as `(\1*)\2+$` followed by testing if `\3`==0 although it didn't improve my regex's overall length at the time, and he came up with the idea to combine the `\3`==0 test and `\1*$` test into one, as `\1*$\3`, thus doing the `\1*$` test at the end instead of the beginning (which sacrifices speed in the name of golf, assuming the regex engine doesn't optimize it). (That is with the group numbering of the fully golfed form mapped onto the snippets.)

I've explained the generalized multiplication algorithm in this post, but since its application to squares is simpler, I'm including an explanation for that here.

To explain why this works, let's rearrange the order of the assertions:

```
(?=
    \1*$       # assert that A divides C-A
)
(?=
    (\1*)\2+$  # iff A*A==C, the first match here must result in \3==0
)
.*$\3          # assert that \3==0

```

We have \\$A^2 \stackrel{?}{=} C\\$. If this assertion were true, we would have:

\\$\begin{aligned}C &= A^2 \\ C-A &= A^2-A \\ &= (A-1)A\end{aligned}\\$

This shows that the assertions made by the regex will hold true if \\$C=A^2\\$:

\\$\begin{aligned}C-A &\equiv 0 \pmod A \\ C-A &\equiv 0 \pmod {A-1}\end{aligned}\\$

Note that in regex, \\$0 \equiv 0 \pmod 0\\$, so the algorithm works for \\$C=1^2\\$ and \\$A=1\\$ without any need for a special case. It also works for \\$C=0\\$, matching it using ECMAScript NPCG (unset/non-participating capture group) behavior – every assertion becomes \\$0 \equiv 0 \pmod 0\\$ and passes.

Assuming \\$A\>1\\$, these can be simplified into:

\\$\begin{aligned}C &\equiv 0 \pmod A \\ C &\equiv 1 \pmod {A-1}\end{aligned}\\$

We now have two coprime moduli, \\$A\\$ and \\$A-1\\$. By the Chinese remainder theorem, there is one and only one integer \\$E\\$ such that \\$0 \le E \< A(A-1)\\$ and the above moduli are satisfied. That applies to any window of the same length, so we can change it to \\$A \< E \le A^2\\$.

\\$A^2-A=(A-1)A\\$ shows there is at least one \\$E\\$ satisfying the moduli: \\$E=A^2\\$. The Chinese remainder theorem shows that there is exactly one \\$E\\$ satisfying the moduli within a certain range. Thus, if we restrict our search to the range \\$A \< E \le A^2\\$, the only value matching both moduli will be \\$E=A^2\\$.

The first thing the regex does is `(x(x*)|)` which subtracts \\$A\\$ from \\$C\\$, so instead of directly searching for a matching \\$E\\$, it is searching for a matching \\$E-A\\$.

`(\1*)\2+$` will first attempt a match using the largest possible number of repetitions of `\1`. Since we already asserted `\1*$`, this will bring us exactly to `$`. But then there will be no room for `\2+`, which is required to have a positive repetition count due to the `+`. So then it starts trying smaller repetition counts for `\1`, giving `\2+` more space in incremental steps of `\1`, thus resulting in incrementally larger repetition counts for `\2`. Note that `\1`\\$=A\\$ and `\2`\\$=A-1\\$. So a successful match of `\2+$` represents a value of \\$E-A\\$ such that \\$E-A \equiv 0 \pmod A\\$ and \\$E-A \equiv 0 \pmod {A-1}\\$.

The regex essentially searches for the smallest \\$A-1 \le E-A \le C-A\\$ satisfying the moduli, or alternatively stated, the smallest \\$2A-1 \le E \le C\\$ satisfying the moduli. Thus, even if \\$C \> A^2\\$, the first matching \\$E\\$ it finds will be \\$E=A^2\\$. Note that the range only had to be restricted to \\$A \< E\\$ via the Chinese remainder theorem, and the regex restricts it to \\$2A-1 \le E\\$ which is a subset of that range.

If no match is found, then \\$C \< A^2\\$ and we get a non-match. If a match is found, and if \\$E-A=C-A\\$, then the `\1` in `(\1*)` will have a repetition count of zero, and `\3` will capture a value of zero. The regex asserts that \\$E=C\\$ by asserting that `\3` has a value of zero; if this matches, then \\$C=A^2\\$ and is indeed a perfect square.

Note that in no point in this reasoning did it matter what the value of \\$A\\$ is. It will only match if \\$A^2=C\\$. Thus, it doesn't matter whether we search for a matching \\$A\\$ from smallest to largest or largest to smallest. The regex does the latter, starting at \\$A=C\\$ and going downward from there in decrements of \\$1\\$.

# Regex (ECMAScript / Python or better), 30 bytes

```
^(x(x*))(?=(\1*)\2+$)\1*$\3|^$

```

Try it online! \- ECMAScript (SpiderMonkey)
Try it online! \- ECMAScript (Node.js - fast)
Try it online! \- Perl
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- PCRE (fastest)
Try it online! \- .NET

This is a port of the 28 byte version, dropping the dependence on ECMAScript NPCG behavior. Matching \\$0^2\\$ is done as a special case, the `^$` alternative at the end.

# Regex (Perl / Java / PCRE / .NET), 12 bytes

```
^(\1xx|^x)*$

```

Try it online! \- Perl (fastest)
Try it online! \- Java
Try it online! \- PCRE (fast)
Try it online! \- .NET

This works by exploiting the fact that \\$(N+1)^2-N^2=2N+1\\$, i.e. the differences between consecutive squares are consecutive odd numbers. The loop is initialized by subtracting \\$1\\$ from tail, which then captures `\1`=\\$1\\$. Every subsequent iteration sets `\1`\\$=\\$`\1`\\$+2\\$ and subtracts `\1` from tail. As a result, the cumulative subtraction from tail is at every step a perfect square, and the `$` will only match at the end if the subtraction culminates in tail equaling zero, meaning the initial value of tail before the loop started was a perfect square.

As such, this regex relies on being able to read the last captured value of group 1 from inside group 1 – a nested backreference, which is a feature not supported by the ECMAScript, Python, or Ruby regex engines.

In this post by primo, it is explained how to extend this method to higher powers and polynomials.

An alternative 12 byte form is `(\1xx|^x?)+$`, but this breaks some nice properties of the form shown above. Most notably, it breaks letting the loop iteration count equal the square root of the number being matched. One of the beauties of keeping that property is that we can return the square root, for example using .NET's balanced groups feature (**25 bytes**):

```
^(?=(\1xx|^x)*$)(?<-1>x)*

```

Try it online! \- .NET

Or using group-building with a branch reset group (**19 bytes**):

```
^(?|\1(\1x)|^(x))*$

```

Try it online! \- Perl
Try it online! \- PCRE

# Regex (Python`regex` / Ruby or better), 22 bytes

```
^((?=(\3xx|^x))(\2))*$

```

Try it online! \- Python `import regex`
Try it online! \- Ruby

In regex flavors with no support for nested backreferences, that feature must be emulated via forward-declared backreferences (which aren't supported either by ECMAScript or Python's built-in `re` module). This is done here by copying back and forth between `\2` and `\3`.

# Answer
> 5 votes
# 05AB1E, 4 bytes

```
Ln¹å

```

Try it online!

# Answer
> 5 votes
# Japt, 3 bytes

```
¬v1

```

Try it online!

Seems to work fine for `2**54-2` in the Japt Interpreter but fails on TIO for some reason...

# Answer
> 5 votes
## SageMath, 9 bytes

```
is_square

```

Try it online

The built-in function does exactly what it says on the tin. Since Sage uses symbolic computation, it's free of computational accuracy errors that plague IEEE-754 floats.

# Answer
> 5 votes
## Haskell, ~~26~~ 24 bytes

```
f n=elem n$map(^2)[0..n]

```

Try it online!

Checks if n is in the list of all squares from `0` to `n`.

# Answer
> 5 votes
# Prolog (SWI), 27 bytes

```
+N:-between(0,N,I),N=:=I*I.

```

Try it online!

## Explanation

Searches through all numbers greater or equal to `0` and less than or equal to `N` and tests whether that number squared is equal to `N`.

# Answer
> 4 votes
# APL, 5 bytes

```
⊢∊⍳×⍳

```

Explanation:

```
⊢           N
  ∊         in
    ⍳        numbers up to N
      ×     times
        ⍳    numbers up to N

```

Test:

```
      ((⊢∊⍳×⍳) ¨ X) ,[÷2] X←⍳25
1 0 0 1 0 0 0 0 1  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

```

# Answer
> 4 votes
# Ruby, 25 bytes

```
Math.sqrt(gets.to_i)%1==0

```

There probably is a shorter way but that's all I found.

Try it online!

# Answer
> 4 votes
# PHP, 21 bytes

```
<?=(-1)**$argn**.5<2;

```

If the square root is not an integer number, `(-1)**$argn**.5` is `NAN`.

# Answer
> 4 votes
# R, 15

```
scan()^.5%%1==0

```

^.5 is less bytes than sqrt(). %%1, the modulus, will result in 0 if answer is an interger. scan() takes user input.

http://www.tutorialspoint.com/execute\_r\_online.php?PID=0Bw\_CjBb95KQMSm1qVktIOUdSSDg

# Answer
> 4 votes
# Factor \+ `math.unicode`, ~~20~~ 17 bytes

Saved 3 bytes thanks to @chunes!

```
[ √ dup ⌊ = ]

```

Try it online!

# Answer
> 3 votes
# PHP, 26 bytes

```
<?=(0^$q=sqrt($argn))==$q;

```

Try it online!

# Answer
> 3 votes
# Java 8, 20 bytes

```
n->Math.sqrt(n)%1==0

```

Input is an `int`.

Try it here.

# Answer
> 3 votes
# Mathematica, 13 bytes

```
AtomQ@Sqrt@#&

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog), 8 bytes

```
0=1|*∘.5

```

Try it online!

`0=` \[is\] zero equal to

`1|` the modulus-1 (i.e. the fractional part) of

`*∘.5` the argument raised to the power of a half

# Answer
> 3 votes
# CJam, 8 bytes

```
ri_mQ2#=

```

Try it online!

### Explanation

Integer square root, square, compare with original number.

# Answer
> 3 votes
# Add++, ~~24~~ ~~13~~ 11 bytes

```
+?
S
%1
N
O

```

Try it online!

I removed the clunky function at the top and rewrote it into the body of the question to remove 11 bytes.

As the first section is already explained below, let's only find out how the new part works

```
S   Square root
%1  Modulo by 1. Produced 0 for integers and a decimal for floats
N   Logical NOT

```

## Old version, 24 bytes

```
D,i,@,1@%!
+?
^.5
$i,x
O

```

Try it online!

The function at the top (`D,i,@,1@%!`) is the main part of the program, so let's go into more detail.

```
D,     Create a function...
  i,   ...called i...
  @,   ...that takes 1 argument (for this example, let's say 3.162 (root 10))
    1  push 1 to the stack; STACK = [1, 3.162]
    @  reverse the stack;   STACK = [3.162, 1]
    %  modulo the stack;    STACK = [0.162]
    !  logical NOT;         STACK = [False]

+?     Add the input to accumulator (x)
^.5    Square root (exponent by 0.5)
$i,x   Apply function i to x
O      Output the result

```

# Answer
> 3 votes
# AWK, 27+2 bytes

```
{x=int($0^0.5);$0=x*x==$1}1

```

Try it online!

Add `+2` bytes for using the `-M` flag for arbitrary precision. I originally used string comparison because large number compared equal, even though they weren't, but the `sqrt` was also returning imprecise values. `2^127-2` should not be a perfect square.

# Answer
> 3 votes
# T-SQL, 38 bytes

```
SELECT IIF(SQRT(a)LIKE'%.%',0,1)FROM t

```

Looks for a decimal point in the square root. `IIF` is specific to MS SQL, tested and works in MS SQL Server 2012.

Input is in column **a** of pre-existing table **t**, per our input rules.

# Answer
> 3 votes
# Ohm, 2 bytes

```
Æ²

```

Uses `CP-437` encoding.

## Explanation

Implicit Input -\> Perfect square built-in -\> Implicit Output...

# Answer
> 3 votes
# Python 3, ~~28 27~~ 25 bytes

* Thanks to @mdahmoune for 1 byte: compare int of root squared with original
* 2 bytes saved: lambda shortened

```
lambda x:int(x**.5)**2==x

```

Try it online!

# Answer
> 2 votes
# Actually, 6 bytes

```
;ur♂²c

```

Try it online!

-2 bytes from Erik the Outgolfer

Explanation:

```
;ur♂²c
;ur       range(n+1) ([0, n])
   ♂²     square each element
     c    does the list contain the input?

```

This takes a while for large inputs - TIO will timeout.

# Answer
> 2 votes
# C (gcc), ~~66~~ ~~43~~ 42 bytes

```
f(float n){return!(sqrt(n)-(int)sqrt(n));}

```

Try it online!

Thanks to TheLethalCoder for the tip!

@hvd Thanks for saving a byte!

# Answer
> 2 votes
# CJam, 12 bytes

```
{_),2f##)!!}

```

Try it online!

# Answer
> 2 votes
# Python, ~~53~~ ~~50~~ ~~49~~ ~~48~~ ~~49~~ 48 bytes

This should in theory work for an input of any size. Returns `True` if the given number is a square, `False` otherwise.

```
f=lambda n,x=0:x<=n if~-(x<=n!=x*x)else f(n,x+1)

```

Try it online!

### Explanation:

```
f=                                                # assign a name so we can call it
  lambda n,x=0:                                   # counter variable x
               x<=n                               # counter bigger than input?
                    if~-(         )               # "negate" inner condition
                         x<=n                     # counter not bigger
                            n!=x*x                # and n not square of x
                                   else f(n,x+1)  # else recurse

```

The condition is just a de-Morgan'd `if x>n or n==x**2`, i.e. we return if the counter is bigger than the input, or we found a proof for squareness.

Saved 1 byte thanks to Gábor Fekete.

# Answer
> 2 votes
# JavaScript on NodeJS & Chrome, 51 bytes

```
// OLD: t=n=>{i=Number.isSafeInteger;return i(n)&&i(n**.5)}

i=Number.isSafeInteger;t=n=>i(n)&&i(n**.5)
// TestCases:
let l=console.log;l(`t(1): ${t(1)}; t(64): ${t(64)}; t(88): ${t(88)};`)

```

Try it online!

# Answer
> 2 votes
# PowerShell, 26 bytes

```
!([math]::Sqrt("$args")%1)

```

Try it online!

# Answer
> 2 votes
# MIPS, 112 bytes

```
main:li $v0,7
syscall
sqrt.d $f0,$f0
mfc1 $a0,$f0
li $v0,1
beqz $a0,t
li $a0,0
syscall
b e
t:li $a0,1
syscall
e:

```

Try it online!

Outputs `1` if the input is square, `0` if not.

## Explanation

```
main:li $v0,7      #Start of program. Load service 7 (read input as float to $f0).
                   #Input can be an integer, but MIPS will interpret it as a float.
syscall            #Execute.

sqrt.d  $f0,$f0    #Overwrite $f0 with its square root, stored as a double.
mfcl    $a0,$f0    #Move $f0 to $a0.
li      $v0,1      #Load service 1 (print int from $a0).
beqz    $a0,t      #Branch to label 't' if $a0 = 0. Otherwise continue.

#If input is non-square...
li      $a0,0      #Load 0 into $a0.
syscall            #Execute (print $a0).
b e                #Branch to label 'e'.

#If input is square...
t:li    $a0,1      #Start of label 't'. Load 1 into $a0.
syscall            #Execute (print $a0).

e:                 #Start of label 'e'. Used to avoid executing 't' when input isn't square.

```

A double in MIPS is 16 hexes. It shares its address with a float containing its low-order 8 hexes (`$f0` in this case). The high-order hexes are stored in the next register (`$f1`), also as a float.

```
          float             double
$f0     0000 0000     1111 1111 0000 0000
$f1     1111 1111

```

Taking the square root of a non-square number requires the entire double in order to be stored, meaning the high and low floats are populated. The square root of a square number only needs a few hexes from the double to be stored, and it is stored specifically in its high-order hexes. This means the low float is left at `0`.

If the low float equals `0`, the input is a square number.

# Answer
> 2 votes
# Whitespace, 95 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_top][T N
T   T   _Read_STDIN_as_integer][N
S S N
_Create_Label_LOOP][S N
S _Duplicate_top][S N
S _Duplicate_top][T S S N
_Multiply_top_two][S S S N
_Push_0][T  T   T   _Retrieve_input][S N
T   _Swap_top_two][T    S S T   _Subtract][S N
S _Duplicate_top][N
T   S S N
_If_0_jump_to_Label_TRUE][N
T   T   T   N
_If_negative_jump_to_Label_FALSE][S S S T   N
_Push_1][T  S S S _Add][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_TRUE][S S S T N
_Push_1][T  N
S T _Print_as_integer][N
N
N
_Stop_program][N
S S T   N
_Create_Label_FALSE][S S S N
_Push_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.

Outputs `1`/`0` for truthy/falsey respectively. A few bytes could be saved if something like `00`/`0` for truthy/falsey is allowed instead.

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

**Explanation in pseudo-code:**

```
Read STDIN as integer, and store it in the heap
Integer i = 0
Start LOOP:
  Integer temp = i*i - input from heap
  If(temp == 0):
    Call function TRUE
  If(temp < 0):
    Call function FALSE
  i = i + 1
  Go to next iteration of LOOP

function TRUE:
  Print 1 as integer
  Stop program
function FALSE:
  Print 0 as integer
  (implicitly stop the program with an error)

```

*Here a port of this approach in Java:*

```
int func(int input){
  for(int i=0; /*infinite loop*/; i++){
    int m = input - i*i;
    if(m==0) return 1;
    if(m<1) return 0;
  }
}

```

Try it online.

# Answer
> 2 votes
# Rockstar, 55 bytes

First time posting a solution to one of my own challenges, if you'll forgive me the indulgence.

Outputs `1` for truthy or nothing for falsey.

```
listen to N
X's0
while N-X
let X be+1
if X*X is N
say 1

```

Try it here (Code will need to be pasted in)

# Answer
> 2 votes
# V (vim), 34 bytes

```
C<C-r>=sqrt(<C-r>")
<esc>:s/.\+\.0\n
:s/.\+/1

```

Try it online!

Returns empty string for a square, `1` for non-square.

## Explanation

```
C<C-r>=sqrt(<C-r>")
C                   cut the input line, enter insert mode
 <C-r>=             evaluate the following math command:
       sqrt(      ) square root of
            <C-r>"  cut input line in register "

<esc>:s/.\+\.0\n/
<esc>               exit insert mode
     :s/.\+\.0\n/   remove instance of <digits>.0
                    this removes a perfect square root.

:s/.\+/1            replace any other non-newline chars left with
                    a single 1.

```

# Answer
> 2 votes
## JavaScript, 44 bytes

```
n=>{for(i=0n;i<=n;){if(i++**2n==n)return 1}}

```

Obligatory bigger but BigInt answer.

Returns `1` if a square, or `undefined` when not a square.

+4 bytes if you want to actually get your answer today:

```
n=>{for(i=0n;i**2n<=n;){if(i++**2n==n)return 1}}

```

# Answer
> 2 votes
# Knight, ~~32~~ ~~33~~ ~~32~~ 30 bytes

```
;=i+1=xP;W!>0=i-i 1|-^i 2xQ1Q0

```

Try it online!

Takes input from standard in, outputs by error code (1 if input is square, 0 otherwise).

Expanded code:

```
;=i +1 (=x PROMPT)
;WHILE !> 0(=i -i 1)
  | (-(^i 2) x)
    QUIT 1
QUIT 0

```

---

+1 bytes from @Jonah because I somehow didn't notice this failed on input `1`
-2 bytes from @Jonah by using short circuit evaluation of `|` instead of `IF`

# Answer
> 1 votes
# Pyth, 5 bytes

```
/^R2h

```

Try it here!

# Answer
> 1 votes
# QBIC, ~~16~~ 18 bytes

```
[:|~b/a=a|_Xq}?b=0

```

*Added two bytes for 0-case*

This runs through `i = 1 ... n` to see if `n / i == i`. Prints `1` if such an `i` is found, prints `-1` for `N=0` and `0` in all other cases. Both `1` and `-1` are considered truthy in QBasic (`-1` being the actual value for true, but `IF (n)` only is false on `n=0`).

# Answer
> 1 votes
# J, 8 bytes

```
(=~<.)%:

```

Explanation:

* `%:` square root
* `=~` is the argument equal to itself
* `<.` floor of
* `=~<.` a J hook, which modifies the right argument by applying `<.`
* so, "is the floor of the square root equal to itself?"

Note: If we want to save the above to a variable as a verb, we must do, eg:

```
issq=.(=~<.)@%:

```

# Answer
> 1 votes
# C, 33 bytes

```
#define f(x)sqrt(x)==(int)sqrt(x)

```

Takes an integer `x`. Checks if the square root of `x` is the square root of `x` rounded to an integer.

Try it online!

# Answer
> 1 votes
# Excel, ~~18~~ 16 bytes

```
=MOD(A1^0.5,1)=0

```

# Answer
> 1 votes
# **Python 3,** ~~39~~ 38 Bytes

```
lambda n:n in(i*i for i in range(n+1))

```

@mathmandan I had the same idea, and this implementation is 1 byte shorter. I wanted to comment on your post but do not yet have 50 reputation. I hope you see this!

This is just brute force, and I did not get it to complete `2147483647` in a reasonable amount of time.

Thanks @DJMcMayhem for suggesting i remove the space after `in`

Try it Online

# Answer
> 1 votes
# Pari/GP, 8 bytes

```
issquare

```

Try it online!

# Answer
> 1 votes
## Pyke, 3 bytes

```
,$P

```

Try it here!

```
,   -   sqrt(input)
 $  -  float(^)
  P - is_int(^)

```

This could be two bytes (and is in older versions) if Pyke didn't helpfully automatically cast the results of sqrt to an integer if it's a square number.

# Answer
> 1 votes
# Charcoal, 8 bytes

```
¬﹪ＸＮ·⁵¦¹

```

Try it online!

### Explanation

```
¬           Not
 ﹪      ¦¹ Modulo 1
   Ｘ  ·⁵   To the power of .5
     Ｎ     Next input as number,

```

# Answer
> 1 votes
# 05AB1E, ~~5~~ 3 bytes

```
t.ï

```

Try it online!

~~Longer than @Erik's but just wanted to give it a shot.~~

Now shorter than Erik's but fails for large numbers...

# Explanation

```
t            # square roots the input
 .ï          # checks if number on stack is an int
             # implicit output of result (0 or 1)

```

# Answer
> 1 votes
# Common Lisp, 30 bytes

```
(defun g(x)(=(mod(sqrt x)1)0))

```

Try it online!

or, with the same length,

```
(defun g(x)(integerp(sqrt x)))

```

# Answer
> 1 votes
# \>\<\>, 22+3 = 25 bytes

```
01-\:*=n;
(?!\1+::*{:}

```

Try it online!

Input is expected on the stack at program start, so +3 bytes for the `-v` flag.

# Answer
> 1 votes
# Ruby, 16 bytes

```
->n{n**0.5%1==0}

```

Trivial solution.

# Answer
> 1 votes
# tinylisp, 67 bytes

```
(load library
(d S(q((n)(contains?(map(q((x)(* x x)))(c 0(1to n)))n

```

Try it online!

Generates a list of numbers from 0 through `n`, maps a lambda function that squares each one, and checks if `n` is in the resulting list of squares. Wildly inefficient, of course.

---

Here's a 77-byte solution that doesn't use the library and runs an order of magnitude faster:

```
(d _(q((x n s)(i(e n s)1(i(l n s)0(_(a x 1)n(a s(a x(a x 1
(d S(q((n)(_ 0 n 0

```

Try it online!

This one uses a helper function `_` which tracks a counter `x` and its square `s`. At each level of recursion, we return success if `s` equals `n` and failure if `s` is greater than `n`; otherwise, if `s` is still less than `n`, we recurse, incrementing `x` and calculating the next `s` by the formula `(x+1)^2 = x^2 + x + x + 1`.

# Answer
> 1 votes
# Julia 0.6, 12 bytes

```
n->√n%1==0

```

Try it online!

Pretty straightforward, having the Unicode  for square-root saves a few bytes.

# Answer
> 1 votes
# Japt `-¡E`, 2 bytes

```
¬d

```

Run it online

# Answer
> 1 votes
# Python 3, ~~27~~ ~~25~~ 24 bytes

saved bytes by simplifying order of operation and comparing roots instead of squared value

```
lambda n:n**.5//1==n**.5

```

Try it online!

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 61 bytes

```
	N =INPUT
T	OUTPUT =EQ(X * X,N) 1
	X =LT(X,N) X + 1	:S(T)
END

```

Try it online!

Increment `X` until either `X ^ 2` is equal to `N` in which case the program outputs `1` or until `X > N` in which case the program outputs nothing.

# Answer
> 1 votes
# k4, ~~12~~ 9 bytes

```
 x=_x:sqrt

```

with num(s) to be checked passed right-side, e.g.

```
 x=_x:sqrt 36 35 25
101b

```

get square root and check if the it is equal to the square root cast to int. if not a square number, the square root will have a decimal place and the cast will cut the decimal off

edit: -3 thanks to ngn :)

---

# K (oK), 8 bytes

```
x=`i$x:%

```

Try it online!

Same logic but in oK, an implementation of k6 (no online k4 interpreter that i'm aware of). Test like:

```
 x=`i$x:% 16 24 81
1 0 1

```

# Answer
> 1 votes
# brainfuck, 42 bytes

```
->>,[[-<<<+>>>]<<++[[-<]<+>>>]<<<[<]>>>]<.

```

Try it online!

Outputs the NUL byte for square numbers and SOH for non-squares. Uses the property that square numbers are the cumulative sum of odd numbers, i.e. 1, 1+3, 1+3+5 etc.

There might be a better way of arranging the cells so as to reduce the number of pointer movements and save bytes.

# Answer
> 1 votes
# Brain-Flak, 92 bytes

```
(({})){{}([(({}[({})({}())])[(())])](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}}{}({()(<{}>)}{}<>)

```

Try it online!

# Answer
> 1 votes
# Forth (gforth), 31 bytes

```
: f dup s>f fsqrt f>s dup * = ;

```

Try it online!

The input is a positive signed single-cell integer (`0 <= n < 2^63` for 64-bit systems). To support full unsigned integer range, do `0 d>f` instead of `s>f`.

Using floats turns out to be shorter than a loop.

### How it works

```
: f ( n -- f )  \ Takes a positive signed int and gives whether it's a square or not
  dup           \ Duplicate n
  s>f fsqrt f>s \ Move to floating-point stack, take sqrt and move back (truncate)
  dup * =       \ Square the result and compare with n
;

```

gforth's comparison operators give -1 for true, 0 for false.

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
Å²

```

Try it online!

A built-in function that checks if a number is a perfect square.

# Answer
> 1 votes
# Vyxal, 2 bytes

```
∆²

```

Try it Online!

Builtin.

# Answer
> 1 votes
# Pyt, 6 bytes

```
Đ0⇹Ř²∈

```

Try it online!

```
Đ                implicit input; Đuplicate
 0               push 0
  ⇹              swap top two items on stack
   Ř²            Řangify, square
     ∈           is input in list of squares?; implicit output

```

# Answer
> 1 votes
# Desmos, 22 bytes

```
f(x)=0^{mod(x^{.5},1)}

```

Try it on Desmos!

# Answer
> 1 votes
# Arturo, 18 bytes

```
$=>[=floor<=sqrt&]

```

Try it

# Answer
> 1 votes
# Nibbles, 5 bytes

```
==^^$-2~@

```

Attempt This Online!

```
==^^$-2~@
==        Equals
  ^    ~   square
   ^ -2     square root
    $        input
        @  input

```

# Answer
> 1 votes
# PowerShell, 22 bytes

```
[math]::sqrt($a)%1-eq0

```

Try it online!

# Answer
> 0 votes
# Python 2, 33 bytes

```
 g = lambda x: (x**.5).is_integer()

```

# Answer
> 0 votes
# Python 2, 25 bytes

```
lambda n:int(n**.5)**2==n

```

Try it online!

# Answer
> 0 votes
# C++, 43 bytes

```
bool c(int n){int t=sqrt(n);return t*t==n;}

```

New version: https://repl.it/repls/CompatibleJumpyCoordinates

If your number is perfect square then it will return 1, otherwise it will return 0;

Old version: https://repl.it/repls/WateryTroubledProjects (not valid because it is the snippet only by @Jonathan Frech)

If your number is perfect square then it will be exited with status 1, otherwise it will not exist;

# Answer
> 0 votes
# BRASCA, 8 bytes

```
ig:s2^=n

```

Try it!

## Explanation

```
ig          - Turn input into digits, and concatenate
  :s2^      - Dupe original number, sqrt it, then square it
      =n    - Are the original and the modified number the same? Print the result (0 or 1)

```

# Answer
> 0 votes
# Stax, 4 bytes

```
à▲⌐°

```

Run and debug it

This is PackedStax, which unpacks to the following 5 bytes:

```
|Q1%!

```

Run and debug it

```
|Q    # input sqrt
  1%  # modulo 1
    ! # logically negated

```

# Answer
> 0 votes
# Vyxal 3, 3 bytes

```
√ᵞ⌊

```

Try it Online!

No built ins, checks if the square root is the same after flooring it.

---
Tags: code-golf, math, number, decision-problem
---