title: The Squaring Sequence

text:
# Question
Title: The Squaring Sequence
Each term in the squaring sequence, \\$x\_n\\$, is created by taking \\$x\_{n-1}\\$, squaring it, and removing all but the first four digits.

The sequence always begins with \\$x\_1 = 1111\\$. Squaring this yields \\$1234321\\$, so \\$x\_2 = 1234\\$

The first few terms are:

```
1111
1234
1522
2316
5363
...

```

---

# The Challenge

Your task is to, given a non-negative integer \\$n\\$, calculate \\$x\_n\\$. You may submit a full program which performs I/O, or a function which takes \\$n\\$ as a parameter.

Your solution can be zero or one indexed, as long as you specify which.

Because all the terms in this sequence are shorter than 5 digits, your code should be as short as possible too. Standard loopholes apply.

May the best golfer win!

---

# Test Cases

*Note: These are 1-indexed.*

```
1   -> 1111
8   -> 6840
15  -> 7584
20  -> 1425
80  -> 4717

```

# Answer
# 05AB1E, ~~8~~ 7 bytes

Code:

```
$Fn4×4£

```

Explanation:

```
$        # Push 1 and the input
 F       # Input times do...
  n      #   Square the number
   4×    #   Repeat that string 4 times
     4£  #   Take the first four characters
         # Output the last computed number

```

Uses the **CP-1252** encoding. Try it online!
> 13 votes

# Answer
# JavaScript (ES7), ~~44~~ ~~43~~ 36 bytes

```
f=n=>--n?(f(n)**2+f).slice(0,4):1111

```

This is a great example of abusing type coercion: `**` converts both its arguments to numbers, and `+` converts both its arguments to strings unless they're both numbers. This means that `f(n)**2+f` first converts `f(n)` to a number and squares it, then concatenates the result with the string representation of `f`. We can then use `.slice` to retrieve the first 4 chars of the string.

Here are a few alternate approaches that don't use strings:

```
f=(n,x=1111)=>x<1e4?--n?f(n,x*x):x:f(n,x/10|0)
f=n=>--n?(x=f(n))*x/(x>3162?1e4:1e3)|0:1111

```

### Test snippet

```
let f=n=>--n?(Math.pow(f(n),2)+f).slice(0,4):1111
```

```
<input id=I type="number" step="1" min="1" value="1"><button onclick="console.log(f(I.value))">Run</button>
```

Note: this uses `Math.pow` because `**` isn't supported in all browsers.
> 25 votes

# Answer
# Python 2, ~~51~~ ~~46~~ 44 Bytes

~~~~I'd like to get rid of the clunky `if` if possible, but I think an `exec` could be shorter..~~ Turns out for the moment that `exec` is shorter.~~ Wrong again! The recursive function returns. This is one-indexed.

```
f=lambda n:1111*(n<2)or int(`f(n-1)**2`[:4])

```

An aleternative 46-byte solution with `exec`:

```
s=1111;exec's=int(`s*s`[:4]);'*input();print s

```

An alternative 49-byte recursive solution:

```
f=lambda n,s=1111:s*0**n or f(n-1,int(`s*2`[:4]))

```

Thanks to Flp.Tkc for saving a byte by reminding me that squaring doesn't need exponentiation :)
> 7 votes

# Answer
## Haskell, 40 bytes

```
((iterate(read.take 4.show.(^2))1111)!!)

```

It's a 0-based sequence. Usage example: `((iterate(read.take 4.show.(^2))1111)!!) 79` -\> `4717`.

How it works:

```
iterate (   ) 1111               -- repeatedly apply a function starting
                                 -- with 1111 and collect the results in a list
                                 -- the function is
           (^2)                  -- square
        show                     -- turn into string
     take 4                      -- take the first 4 chars
  read                           -- turn back to number
                     !!          -- finally pick the nth element from the list

```
> 6 votes

# Answer
# , 19 bytes

```
4é1Àñ|C="*"
5|D

```

Try it online!

This uses 0-based indexing.

Of course, since numbers aren't exactly V's *forte*, this isn't very golfy. However, it does show one nice advantage V has over vim. You can run a macro *0* times, which is not possible in vim since '0' is a command not a count.

This contains many unprintable characters, so here is a hexdump:

```
0000000: 34e9 31c0 f17c 4312 3d12 222a 1222 0a1b  4.1..|C.=."*."..
0000010: 357c 44                                  5|D

```

And here is a readable version:

```
4é1Àñ|C<C-r>=<C-r>"*<C-r>"
<esc>5|D

```

Explanation:

```
4                           " 4 times:
 é1                         " Insert a '1'
   Àñ                       " Arg1 times:
     |                      "   Move to the first character on this line
      C                     "   Delete this whole line and enter insert mode
       <C-r>=               "   Insert the following evaluated as vimscript:
             <C-r>"         "     Insert what we just deleted
                   *        "     Times
                    <C-r>"  "     What we just deleted
<esc>                       "   Escape to normal mode
     5|                     "   Move to the fifth column on this line
       D                    "   And delete until the end of this line
                            " The second 'ñ' is added implicitly

```
> 6 votes

# Answer
## Perl, 37 bytes

36 bytes of code + `-p` flag.

```
$\=1x4;$\=substr$\*$\,0,4while--$_}{

```

To run it:

```
perl -pe '$\=1x4;$\=substr$\*$\,0,4while--$_}{' <<< 80

```
> 6 votes

# Answer
# Jelly, ~~12~~ 9 bytes

-3 bytes thanks to Dennis using 1-based indexing and the  mold/reshape atom. Golfing suggestions welcome! Try it online!

```
²Dṁ4Ḍ
1Ç¡

```

**Ungolfing**

```
Helper link
²       Square.
 D      Integer to decimal (a list of digits).
  ṁ4    Mold/reshape list_of_digits to be 4 digits long.
    Ḍ   Decimal to integer.

Main link: implicit left argument n
1     Start with the nilad 1.
 Ç¡   Call the helper link n times.

```
> 6 votes

# Answer
# Mathematica, 48 bytes

```
Nest[⌊10^(3-⌊t=2Log[10,#]⌋+t)⌋&,1111,#]&

```

Unnamed function taking an integer argument; 0-indexed. Uses four three-byte characters `⌊⌊⌋⌋`: Mathematica uses either `Floor[x]` or `⌊x⌋` to round a real number down to an integer, and the latter is generally one fewer byte. The command names in Mathematica for converting integers to strings are too long, so instead we do a mathematical calculation to find the first four digits of x^2: we take the base-10 logarithm of x^2, subtract its integer part, raise 10 back to that power, and multiply by 1000 and round down.

tl;dr: logarithms ftw
> 6 votes

# Answer
# APL (Dyalog Extended), 13 bytes

-2 (changing the input method) thanks to @Razetime

```
{⍎4⍴⍕⍵*2}⍣⎕⊢1

```

Explanation:

```
{⍎4⍴⍕⍵*2}⍣⎕⊢1     ⍝ apply the dfn input times
            1     ⍝ .. with initial argument 1
     ⍵*2          ⍝ current value squared
 ⍎4⍴⍕             ⍝ take first 4 digits

```

Try it online!
> 5 votes

# Answer
## Powershell, ~~73~~ 55 bytes

Huge thanks to TimmyD for shaving off 18 bytes!

Code:

`for($A=1111;$args[0]---1;$A=-join"$(+$A*$A)"[0..3]){}$A`

~~`$A=1111;1..($n=2)|%{[string]$B=[math]::pow($A,2);$A=$B.substring(0,4)};$A`~~

`$n` is **n** in **xn-1**

Explanation and exploded code:

```
$A=1111                            #starting number
$n=4                               #n in formula
for($i=0; $i -lt $n;$i++)          #loop n times
{
    [string]$B=[math]::pow($A,2)   #create a new string $B and set it to $A raised to the power of 2
    $A=$B.substring(0,4)           #set $A to the first 4 characters of $B
}
$A                             #print $A

```

Some notes:

* Powershell lets you assign variables in the same statements where you reference them. For example, `1..($n=4)|%` will set $n to 4 and then start a loop that runs $n times. `1` can be changed to any integer and it will loop $n-\[your integer\]+1 times.
* The default data type when using `[math]::` in Powershell is a double. In the code above, we have to explicitly cast `$B` to a string so that we can call `.substring()` on it because there is no `.substring()` function for doubles in Powershell.
> 4 votes

# Answer
# Python 2,  ~~44~~  41 bytes

-3 bytes thanks to xnor (use an integer division to avoid `and`)

```
f=lambda n:int(1/n*1111or`f(n-1)**2`[:4])

```

**repl.it**

1-based recursive function.

When `n>1` the integer division, `1/n`, results in `0`, then `0*1111=0` which is falsey, so the right of the `or` is evaluated, which takes the first four characters of the representation of the square of the `n-1`th result; this is then cast to an `int`.

When `n=1` the integer division, `1/n`, results in `1`, then `1*1111=1111`, which is truthy, and the `int` `1111` cast to an `int` is `1111`.
> 4 votes

# Answer
# Groovy, 49 bytes

```
{x=1111;(it-1).times{x="${x**2}"[0..3] as int};x}

```
> 3 votes

# Answer
# PHP, ~~55~~ 52 bytes

Saved 3 bytes thanks to @user59178

```
for($i=1111;$argv[1]--;)$i=substr($i**2,0,4);echo$i;

```

Run from command line, zero-indexed.

Thanks for not caring about what type my variables are, PHP! Here we simply square the number and trim off everything past the first 4 digits, casually alternating between number and string without a care in the world.
> 3 votes

# Answer
# MATL, ~~14~~, 13 bytes

```
1111G:"UV4:)U

```

Try it online!

Explanation:

```
1111            % Push 1111
    G           % Push input
     :"         % Input times:
       U        %   Square the top of the stack
        V       %   Convert it to a string
         4:)    %   Take the first four digits
            U   %   Convert it back to a number
                % Implictly display

```
> 3 votes

# Answer
## Pyke, 10 bytes

```
1RVX`4*4<b

```

Try it here!
> 3 votes

# Answer
# R, ~~58~~ ~~56~~ ~~55~~ 53 bytes

```
x=3334;for(e in N<-scan():1)x=x^2%/%10^(3+(x>3162));x

```

Takes `N` from stdin. 3334 is practically X\_0, which is needed because the for-loop needs to be executed at least once (it would be longer to skip).

R really is a terrible language for taking the first four digits of a number, but since the number of cases are limited, we only have to worry about the squares of `x<3163` and `x>3162`, the former yield a 6 digit number, the latter a 7 digit number.

The rest is pretty straightforward, `%/%` divides and ignores the remainder. `x` is printed to stdout.

Saved 2 bytes thanks to @ETHproductions
> 3 votes

# Answer
# Pushy, 20 bytes

```
1111@:2esL4-:.;Kjk;#

```

Try it online!

Note this is 1-indexed.

```
            % Implicit: N is on stack
1111@       % Push 1111, and then reverse stack to get [1111, n]
:           % N times do: (this consumes N)
 2e         %   Square last term
 s          %   Split into individual digits
 L4-:.;     %   Get stack length -4, pop that many times
 Kj         %   Join remaining digits (Uses flag "K" for whole stack)
 k          %   Set "K" flag to false, so operations only affect last item
;           % End loop.
#           % Output final calculated term

```
> 3 votes

# Answer
# Javagony \- 153 bytes

Javagony is a restricted version of Java, that doesn't allow any control flow except recursion and `try-catch`, no for loops, while loops, or if's. Coding in it is a pretty fun exercise, but frustrating. Not that regular Java isn't nearly as frustrating by itself.

```
int a(int i){return a(i-1,1111);}int a(int i,int n){try{int x=1/i;return a(i-1,Integer.parseInt((n*n+"").substring(0,4)));}catch(Exception e){return n;}}

```
> 3 votes

# Answer
# cQuents, 14 bytes

```
=1111:(ZZ)[:4]

```

Try it online!

1-indexed.

## Explanation

```
=1111           first term is 1111
     :          given n, output nth term, otherwise output full sequence
                each term equals
      (ZZ)                       previous term * previous term
          [:4]                                                 [:4] (python slicing)

```
> 3 votes

# Answer
# Brachylog, 18 bytes

```
,1111:?:{^@[.l4,}i

```

Try it online!

This answer is 0-indexed.

### Explanation

```
,1111:?:{       }i      Iteratively call Input times the predicate in brackets starting with
                          input 1111:

         ^                  Square
          @[.               Output is a prefix of the square
            .l4,            Its length is 4

```
> 2 votes

# Answer
# C#, 64 60 bytes

*Saved 4 bytes by following Olivier Grégoire's comment on a Java answer!*

```
n=>{int x=1111;for(;n-->1;)for(x*=x;x>1e4;x/=10);return x;};

```

Previous version (**64 bytes**):

```
n=>{int x=1111;while(n-->1){x*=x;while(x>9999)x/=10;}return x;};

```

Full program with ungolfed method and test cases:

```
using System;

namespace SquaringSequence
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int, int> f = n =>
            {
                int x = 1111;
                while (n-- > 1)
                {
                    x *= x;
                    while (x > 9999)
                        x /= 10;
                }
                return x;
            };

            // test cases:
            Console.WriteLine(f(1));    // 1111
            Console.WriteLine(f(8));    // 6840
            Console.WriteLine(f(15));   // 7584
            Console.WriteLine(f(20));   // 1425
            Console.WriteLine(f(80));   // 4717
        }
    }
}

```
> 2 votes

# Answer
## Batch, 82 bytes

```
@set n=1111
@for /l %%i in (1,1,%1)do @set/an*=n&call set n=%%n:~0,4%%
@echo %n%

```

Like Perl, integers are strings, but unlike Perl I can only take the substring of a variable, and taking substrings inside a loop is somewhat awkward.
> 2 votes

# Answer
# Pyth, ~~13~~ 12 bytes

*Thanks to @Jakube for -1 byte*

```
us<*4`*GG4Q1

```

A program that takes input of a 1-indexed integer and prints the result.

Test suite

This uses a similar approach to @Adnan's answer.

**How it works**

```
us<*4`*GG4Q1  Program. Input: Q
u         Q1  Execute the following Q times, starting at 1, with variable G:
      *GG      Yield G*G
     `          Convert to string
   *4           Repeat 4 times
  <      4      Yield first 4 characters
 s              Convert to integer
              Implicitly print

```
> 2 votes

# Answer
# C, 56 bytes

```
a;s(n){for(a=1111;--n;)a=a*a/(a>3162?1e4:1e3);return a;}

```

One-indexed.
> 2 votes

# Answer
# Clojure, 76 bytes

```
(defn s[n](if(= n 1)1111(read-string(subs(str(*(s(dec n))(s(dec n))))0 4))))

```

First Clojure golf (seems like a nice language). This is 1-indexed.

Will explain the code later.
> 2 votes

# Answer
# Ruby, 47 bytes

First golf! Saves bytes with `-n` option (but still count as 1! :)).

```
a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a

```

0-indexed. To run it:

```
ruby -ne 'a=1111;$_.to_i.times{a="#{a*a}"[0,4].to_i};p a' <<< 80

```
> 2 votes

# Answer
# GolfScript, 15 bytes

```
~1111\{.*`4<~}*

```

Try it online!

0-indexed

```
~                 # Parse n to a number
 1111             # Push 1111
     \{      }*   # Execute this block n times
       .*         # Square the number
         `        # Parse it to a string
          4<      # Get the first 4 digits
            ~     # Parse it back to a number

```
> 2 votes

# Answer
# Japt `-mh`, 9 bytes

```
T=Â4î1wT²

```

Try it

```
T=Â4î1wT²     :Implicit map of range [0,input)
T=            :Assign to variable T (initially 0)
  Â           :Bitwise NOT of bitwise NOT of (i.e., cast to an integer)
   4î         :Mould to length 4 string
     1w       :  Maximum of 1 and
       T²     :  T squared
              :Implicit output of final result

```

## No Flags, ~~12~~ 10 bytes

1-indexed, returning a string

```
@4îX*X}g1ì

```

Try it

```
@4îX*X}g1ì     :Implicit input of input of integer U
@              :Function taking an integer X as argument
 4îX*X         :  Mould X*X to length 4
      }        :End function
       g       :Repeatedly take the last element of the following array, pass it through that function, push the result and return the Uth element
        1ì     :  Convert 1 to digit array

```
> 2 votes

# Answer
# Vyxal, ~~6~~ 5 bytes

```
Ṫ(²4Ẏ

```

Try it online, or verify all test cases.

Explanation:

```
Ṫ      # Pop, push 1 then the input
 (     # [Input] times:
  ²    #   Square
   4Ẏ  #   Get the first 4 digits

```
> 2 votes

# Answer
# TI-Basic, 31 bytes

```
Input N
1111
For(I,2,N
int(Ans²/₁₀^(-3+int(log(Ans²
End
Ans

```

1-indexed input. `-` represents the negative symbol.
> 2 votes

# Answer
# Excel VBA, 42 bytes

```
v=1111:For i=2To[A1]:v=Left(v^2,4):Next:?v

```

Input is in cell `A1` of the active sheet. Code is run in the immediate window. Output is to the immediate window. Here's the result for `80` as an input:
> 2 votes

# Answer
# Java 8, ~~82~~ 59 bytes

Saved 23 bytes thanks to help from commenters @adrianmp and @OlivierGrégoire

```
n->{int x=1111;while(--n>0)for(x*=x;x>1e4;x/=10);return x;}

```

Each iteration, we square the number, then loop and shrink it by factors of 10 until it's a 4 digit number. Repeat this process `n` times and return.
> 1 votes

# Answer
## CJam, 15 bytes

```
'14*ri{i2#s4<}*

```

Uses 0-based indexing.

Try it online!
> 1 votes

# Answer
# Java 8, ~~77~~ ~~93~~ ~~74~~ ~~71~~ ~~69~~ 78 bytes

~~```
int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}

x->{int n=1111;int m=1;while(x>m++){n=Integer.parseInt((n*n+"").substring(0,4));}return n;}

x->{int n=1111;for(;--x>0;){n=Integer.parseInt((n*n+"").substring(0,4));}}

x->{long n=1111;for(;--x>0;){n=Long.valueOf((n*n+"").substring(0,4));}}

```~~
```
x->{long n=1111;for(;--x>0;)n=Long.valueOf((n*n+"").substring(0,4));return n;}

```

Each repetition makes `n` the first 4 characters of `n*n`.

Try Java online!

### Post history:

* 77 bytes: initial code (incomplete)
* +16 bytes, by Olivier Grégoire: completed code by making it a Lambda function.
* -19 bytes: replace `while` with `for` cycle.
* -4 bytes: used `long`s instead of `int`s
* -2 bytes, by Roman Gräf: removed unnecessary brackets
* +9 bytes, missing `return` statement

**Thanks to @OlivierGrégoire and @RomanGräf for pointing out some issues!**

Wait, Java beats... (drumroll) Clojure *and* Matlab here! A big applause to Java please!
> 1 votes

# Answer
# Perl 6, 36 bytes

```
{(1111,{+$_².substr(0,4)}...*)[$_]}

```

## Explanation:

```
{                                 } # bare block lambda
  1111,                  ...        # sequence generator
                            *       # without a limit
       {                }           # lambda used to generate the next value
         $_²                        # start by squaring the previous value
            .substr(0,4)            # take only the first four digits
        +                           # make it numeric ( not necessary )
 (                           )[$_]  # return the requested value

```

## Test:

```
say {(1111,{+$_².substr(0,4)}...*)[$_]}( 1,8,15,20,80 X- 1 ).perl
# (1111, 6840, 7584, 1425, 4717)

```
> 1 votes

# Answer
# GNU Awk, 41 bytes

Pretty straightforward since you can easily mix math and string manipulations.

```
{for(x=1111;--$1;x=substr(x*x,1,4));}$1=x

```

Accepts zero or more positive numbers *n* (1-indexed), one number per line, on stdin. Outputs results *xn*, one result per line, on stdout.

Sample input/output:

```
% awk -f sqrseq.awk
1
1111
8
6840
15
7584
20
1425
80
4717
%

```
> 1 votes

# Answer
# Matlab, ~~79~~, 78 Bytes

```
function a=s(n)
if n<2;a=1111; else f=s(n-1);a=fix(f^2/10^(3+(f>1e7^.5)));end

```

Test cases:

```
s(79) = 2172
s(49) = 8059
s(6)  = 2876

```

Not an amazing solution. I'm sure there must be a better way to truncate to 4 digits but I don't know today.

Edit: Shaved a byte by setting 0.5 -\> .5
> 1 votes

# Answer
# Java, ~~79~~ ~~67~~ ~~66~~ 64 bytes

* Version 2.2/**64** bytes:

Thanks to @Oliver Grégoire.

```
int a(int i){i=i<2?1111:a(--i);for(i*=i;i>1e4;)i/=10;return i;}

```
* Version 2.1/**66** bytes:

Thanks to @ETHProduction.

```
long a(long i){i=i<2?1111:a(--i);for(i*=i;i>1e4;)i/=10;return i;}

```
* Version 2.0/**67** bytes:

Replaced substring and stuff with the idea from @Xanderhall

```
long a(long i){i=i<2?1111:a(--i);i*=i;for(;i>1e4;)i/=10;return i;}

```
* Version 1.0/**79** bytes:

Although there are shorter solutions I wanted to post one recursive:). And I am the shortest "real" function:). ***Edit:*** Seems like I am the shortest now:)))

```
long a(long i){i=i<2?1111:a(--i);return Long.valueOf((i*i+"").substring(0,4));}

```
> 1 votes

# Answer
# Perl, 36 bytes

A different approach from the other Perl solution, leading to slightly shorter code. No command-line arguments are needed (other than the usual version selection argument, `-M5.010`, which doesn't count against the byte count), meaning that this is the same amount of code but with fewer penalties, giving a better overall score.

```
say+eval'($&*$&||1x4)=~/(....)/;'x<>

```

We create a loop Underload-style via repeating and `eval`-ing a string; I experimented with starting the string in the middle, but starting it at the start turns out to be shortest. We multiply `$&` (the result of the last regex match) by itself to square it; if the result's zero, we use `1x4` (i.e. `1111`; Perl has an operator for repeating things, including digits of a number) instead of the result. Then we regex the first four characters. The whole thing runs in list context due to being inside `say`, thus the final result of the `eval` will be the contents of the parentheses of the final match.
> 1 votes

# Answer
# Husk, 11 bytes

```
¡öd↑4d□1111

```

Try it online!
> 1 votes

# Answer
# Stax, 8 bytes

```
å\S∩♪öH╠

```

Run and debug it
> 1 votes

# Answer
# JavaScript, 35 bytes

```
n=>n?(''+f(n-1)**2).slice(0,4):1111

```

Zero-indexed. Outputs a string if n \>= 0 and the number 1111 if n == 0.
> 1 votes

# Answer
# \>\<\> (Fish), 59 bytes

```
1e4f*+f*+$v /a,:1%-11!.|
:*:$v!?:-1<$^?)+*f+*f+*f2e6a
 ;n$<

```

Try it

# Explanation

Red loop repeatedly squares. Blue subloop divides by 10 while the value is greater than or equal to 10000.

`1e4` is 1111 encoded as base 15. Then repeated `f*+` sums it.

`a6e2` is `10000` encoded as base 15.

I'm not sure if my base 15 encoding is optimal. Maybe some string encoding with base 255 would be better? But then how to properly add the elements? Hmm this could be a challenge.
> 1 votes

# Answer
# MathGolf, 8 bytes

```
1kÆ²░4<i

```

Try it online.

**Explanation:**

```
1         # Push 1
 k        # Push the input-integer
  Æ       # Pop and loop that many times, using 5 characters as inner code-block:
   ²      #  Square the current integer
    ░     #  Convert it to a string
     4<   #  Pop and leave the first 4 characters/digits
       i  #  Convert it back to an integer
          # (after the loop, the entire stack is joined together and output implicitly)

```
> 1 votes

# Answer
# Go, 79 bytes

```
func f(n int)int{i,a:=0,1111
for;i<n;i++{for s:=a*a;s>999;s/=10{a=s}}
return a}

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2, 8 bytes

```
«¥[s{²4ɱ

```

Attempt This Online!

0-indexed.

#### Explanation

```
«¥[s{²4ɱ  # Implicit input
«¥[       # Push compressed integer 1111
   s{     # Repeat input number of times:
     ²    #  Square top of stack
      4ɱ  #  Take the first four characters
          # Implicit output

```
> 1 votes

# Answer
# Julia 1.0, 42 bytes

```
!x=parse(Int,("$(1(x<2||!~-x)^2)"^4)[1:4])

```

Try it online!
> 1 votes

# Answer
## QBIC, ~~43~~ 41 bytes

```
#1111|:[a-1|f=!A! A=$LEFT$|(!f*f/z$,5)]?A

```

Way too much going on in here... Time to implement Substring in QBIC.

Explanation:

```
#1111|                     Define string constant A$ as '1111'
:                          Get CMD line param for N, called 'a'
[a-1|                      FOR 'b' = 1 to 'a'-1
  f=!A!                    Make 'f' be A$ cast to num

             f*f/z         Square 'f', and since we only want the first 4 digits,
                           divide it by 10 (z=10). This prevents that QBASIC
                           switches to E^ notation because f^2 is too large
    $LEFT$|(!       $|,5)  Cast it to string, take the first 5 positions (QBASIC
                           adds a leading space on cast-to-num...)
  A=                       And assign to A$
]                          END FOR
?A                         Print the latest value of A$, end

```

Verified for all test cases.
> 0 votes

# Answer
# Wonder, 28 bytes

```
@:^#0(genc@><""tk4^#0 2)1111

```

Usage:

```
(@:^#0(genc@><""tk4^#0 2)1111)79

```

Simply gets the *n* th item from an infinite list of squaring sequence numbers. Zero-indexed.

More readable:

```
@
  iget #0
    (
      genc@
        join "" tk 4 ^ #0 2
    ) 1111

```
> 0 votes

# Answer
## Pip, 13 bytes

```
Lao:(o*o)@<4o

```

1-indexed. Takes input as a command-line argument. Try it online!

### Explanation

Same algorithm as most of the 1-indexed golflang answers.

```
               Implicit: a is 1st cmdline arg; o is 1
La             Loop a times:
  o:             Assign this expression to o:
         @<4     Leftmost four characters of
    (o*o)        o squared (parens necessary for precedence)
            o  Print final value of o

```

The first step, from `1` to `1111`, works without any explicit string repetition: string slicing in Pip repeats the string as necessary until the slice index is valid. So "leftmost four characters of `1`" gives `1111`.
> 0 votes

# Answer
# Minkolang v0.15, ~~43~~ ~~40~~ 33 bytes

```
'1111'nd?C[2;6ZrI4-[x]r6$Z]N.CxN.

```

**0-indexed**

Try it online! (for `n=2`)

### Explanation

```
'1111'                            push this number
      n                           push input as number
       d                          duplicate
        ?                         check if it is 0:

```

If input is `0`: *(the reason `0` has to be handled specially is that otherwise Minkolang gets confused with the for-loops and `0`iterations that you get an error)*

```
         C                        start comment
           ... C                  end comment
                x                 delete value at top of stack (ie 0)
                 N.               output as number and end program

```

If input is `> 0`:

```
         C                        gets jumped over (since input is true)
          [               ]       start for-loop with the input as the number of iterations
           2;                      pushes 2, and raises the number by 2 (ie squares it)
             6Z                    converts number to string
               r                   reverses it
                I4-                pushes the length of the stack (ie the string value of the number) and subtracts it by 4 (so we now how many of the string to discard of)
                   [x]             discard the top of the stack by that many times
                      r            reverses stack
                       6$Z         converts it to a number
                                   for-loop ends
                           N.     output stack as number and end program

```
> 0 votes

# Answer
# Python 3, 67 Bytes

Indexed at 1

```
a=1111
for _ in range(int(input())-1):a=str(int(a)**2)[:4]
print(a)

```

I was originally going to do this as a list comprehension, but I realised that I couldn't receive the last item in the list in order to square it.
> 0 votes

# Answer
# **C**, 53 52 bytes

```
a;s(n){return n?(a=s(n-1))*a/(a>3162?1e4:1e3):1111;}

```

Zero based. First timer - This is a recursive variation on the earlier solution (expressed in the same way), as requested.
> 0 votes

# Answer
# Scala, 44 bytes

```
Stream.iterate(1111)(n=>n*n+"" take 4 toInt)

```

This is an expression which evaluates to a `Stream[Int]`, which is an infinte sequence of integers. In scala, `Stream[A]` extends `(Int => A)`, which means that a Stream is a function from an index to the element at that index.

### Explantion:

```
Stream.iterate( //create an infinite Sequence,
    1111        //starting with 1111,
  )(            //by calculating the next element with the following function:
    n=>
      n*n       //square the previous element
      +""       //convert it to a string
      take 4    //take the first 4 characters and drop the rest
      toInt     //convert the string back to an int
  )

```
> 0 votes

# Answer
# Swift, 80 Bytes

```
func s(i:Int)->Int{var c=1111;for _ in 0..<i{c*=c;while c>9999{c/=10}};return c}

```

---

**Ungolfed**

```
func squaringSequence(index: Int) -> Int {
    var currentNum = 1111

    for _ in 0 ..< index {
        currentNum *= currentNum

        while currentNum > 9999 {
            currentNum /= 10
        }
    }

    return currentNum
}

```

Due to the pretty-verbose nature of string manipulation in Swift, in which converting an Int to a String, getting the first four characters, and converting back might look something like this:

```
let str = String(num);
num = Int(str[str.startIndex ..< str.index(str.startIndex, offsetBy: 4)])!

```

I'm opting to get the first four digits by dividing by 10 as needed.
> 0 votes

# Answer
# RProgN, 19 Bytes

```
~{2^''.4m14¢}\*1\C

```

RProgN continues to be amazing average! Although it easily passes the score of verbose languages, it still chokes in comparison to other golfier languages.

## Explained

```
~{2^''.4m14¢}\*1\C  # Main link
~                    # Zero Space Segment
 {          }       # Define anonymous function
  2^                # Square the top of the stack
    ''.             # Convert to a string.
       4m           # Repeated 4 times.
         14¢        # Push back only the first 4 letters.
             \*     # Multiplied by the implicit input, Creating another anonymous function that calls this one n times.
               1\C  # Push 1 to the stack, and call the chained function.

```

Try it Online!
> 0 votes

# Answer
# Retina, 77 bytes

Sequence is zero-indexed. Doesn't work for `n > 1` in TIO because of memory constraints. Byte count assumes ISO 8859-1 encoding.

```
$
¶1111
{`(?!0¶).+
$*
(?<=1¶(1*))1(?=(1*))
1$1$2
^1

M%`1
}`(\d{4}).*$
$1
0¶

```

**Try it online**

**Explanation:**

```
$                           # Append a newline and the starting number
¶1111
{`(?!0¶).+                  # Begin loop. If counter is not zero, convert numbers to unary
$*
(?<=1¶(1*))1(?=(1*))        # If the counter >= 1, replace each digit with entire number
1$1$2                       #   (This squares the number)
^1                          # Counter -= 1

M%`1                        # Convert each line's numbers back to decimal
}`(\d{4}).*$                # Keep only first four digits. End loop
$1
0¶                          # Remove the counter

```
> 0 votes

# Answer
## Clojure, 70 bytes

```
#(first(drop %(iterate(fn[i](read-string(subs(str(* i i))0 4)))1111)))

```

Zero-based indexing. Iterates a function which returns first 4 characters of the string representation of the squared integer value.
> 0 votes

# Answer
# C++ (clang), 52 bytes

```
void s(int&n){n=--n?s(n),n*n/1e3/(n<3163?:10):1111;}

```

Port of Lynn's C answer using recursion, is 1 indexed and returns via out parameter.

Try it online!
> 0 votes

# Answer
# brev, 66 bytes

```
(fn(eif x(strse*((fn(* x x))(f(- x 1)))"^...."(m 0)0)1111))

```

There's no `square` unless I import the math lib so `(fn(* x x))` had to do. Using a regex to yank the first four digits. This is zero-indexed.
> 0 votes

# Answer
# J-uby, 28 bytes

0-indexed.

```
(~:**&2|S|~:[]&4&0|Z)+[1111]

```

Attempt This Online!

## Explanation

```
(~:** & 2 | S | ~:[] & 4 & 0 | Z) + [1111]

(                               ) + [1111]  # Iterate n times starting with initial value 1111
 ~:** & 2 |                                 #   Square, then
            S |                             #   Convert to string, then
                ~:[] & 4 & 0 |              #   Get first 4 characters, then
                               Z            #   Convert to int

```
> 0 votes

# Answer
# , 26 bytes

```
{"J"$4#string x*x}/[;1111]

```

# k, 18 bytes

```
{.:4#$x*x}/[;1111]

```
> 0 votes

# Answer
# Python 3, 76 bytes

```
x=1111
n=int(input())
for y in range(n-1):
    x=int(str(x**2)[:4])
print(x)

```

Try it online!
> 0 votes

# Answer
# \>\<\>, ~~40~~ 36 bytes

```
"e"b*>$1-:@?!n:*v
%1:,av?  (*"dd":<-

```

Try it online!

**Explanation**

```
                   # we call the input n
"e"b*              # initialize number as 1111
     >$1-:@?!n     # calculate n-1, if 0 then print number
              :*v  # else, square and move to row 2
     v?  (*"dd":<- # if number is less than 10000, move to row 2
%1:,a              # else divide by 10 and mod away the decimals to get an int

```
> 0 votes

---
Tags: code-golf, math, sequence, integer
---


title: Sum square difference

text:
# Question
Title: Sum square difference
The sum of the squares of the first ten natural numbers is, \\$1^2 + 2^2 + \dots + 10^2 = 385\\$

The square of the sum of the first ten natural numbers is,

\\$(1 + 2 + ... + 10)^2 = 55^2 = 3025\\$

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is

\\$3025 − 385 = 2640\\$

For a given input n, find the difference between the sum of the squares of the first n natural numbers and the square of the sum.

Test cases

```
1       => 0
2       => 4
3       => 22
10      => 2640
24      => 85100
100     => 25164150

```

This challenge was first announced at Project Euler #6.

### Winning Criteria

* There are no rules about what should be the behavior with negative or zero input.
* The shortest answer wins.

# Answer
> 14 votes
# Jelly,  ~~5~~  4 bytes

```
Ḋ²ḋṖ

```

**Try it online!**

### How?

Implements \\$\sum\_{i=2}^n{(i^2(i-1))}\\$...

```
Ḋ²ḋṖ - Link: non-negative integer, n
Ḋ    - dequeue (implicit range)       [2,3,4,5,...,n]
 ²   - square (vectorises)            [4,9,16,25,...,n*n]
   Ṗ - pop (implicit range)           [1,2,3,4,...,n-1]
  ḋ  - dot product                    4*1+9*2+16*3+25*4+...+n*n*(n-1)

```

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

-1 thanks to xnor

```
lambda n:(n**3-n)*(n/4+1/6)

```

**Try it online!**

Implements \\$n(n-1)(n+1)(3n+2)/12\\$

---

Python 2,  ~~29~~  28 bytes: `lambda n:(n**3-n)*(3*n+2)/12`

# Answer
> 8 votes
# APL (Dyalog Unicode), 10 bytes

```
1⊥⍳×⍳×1-⍨⍳

```

Try it online!

### How it works

```
1⊥⍳×⍳×1-⍨⍳
  ⍳×⍳×1-⍨⍳  Compute (x^3 - x^2) for 1..n
1⊥          Sum

```

Uses the fact that "square of sum" is equal to "sum of cubes".

# Answer
> 7 votes
# Brain-Flak, ~~74~~ ~~72~~ ~~68~~ 64 bytes

```
((([{}])){({}())}{})([{({}())({})}{}]{(({}())){({})({}())}{}}{})

```

Try it online!

Pretty simple way of doing it with a couple of tricky shifts. Hopefully someone will find some more tricks to make this even shorter.

# Answer
> 7 votes
# TI-Basic (TI-83 series), ~~12~~ 11 bytes

```
sum(Ans² nCr 2/{2,3Ans

```

Implements \\$\binom{n^2}{2}(\frac12 + \frac1{3n})\\$. Takes input in `Ans`: for example, run `10:prgmX` to compute the result for input `10`.

# Answer
> 5 votes
# Japt `-x`, ~~9~~ ~~8~~ ~~5~~ 4 bytes

```
õ²í*

```

Try it

---

## Explanation

```
õ        :Range [1,input]
 ²       :Square each
  í      :Interleave with 0-based indices
   *     :Reduce each pair by multiplication
         :Implicit output of the sum of the resulting array

```

# Answer
> 5 votes
# JavaScript, 20 bytes

```
f=n=>n&&n*n*--n+f(n)

```

Try it online

# Answer
> 5 votes
# Charcoal, ~~12~~ 10 bytes

```
ＩΣＥＮ×ιＸ⊕ι²

```

Try it online! Link is to verbose version of code. Explanation: \\$ ( \sum\_1^n x )^2 = \sum\_1^n x^3 \\$ so \\$ ( \sum\_1^n x )^2 - \sum\_1^n x^2 = \sum\_1^n (x^3 - x^2) = \sum\_1^n (x - 1)x^2 = \sum\_0^{n-1} x(x + 1)^2 \\$.

```
   Ｎ        Input number
  Ｅ         Map over implicit range i.e. 0 .. n - 1
        ι   Current value
       ⊕    Incremented
         ²  Literal 2
      Ｘ     Power
     ι      Current value
    ×       Multiply
 Σ          Sum
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 5 votes
# Perl 6, 22 bytes

```
{sum (1..$_)>>²Z*^$_}

```

Try it online!

Uses the construction \\$ \sum\_{i=1}^n {(i^2(i-1))} \\$

# Answer
> 4 votes
# dc, 16 bytes

```
?dd3^r-r3*2+*C/p

```

Implements \\$(n^3-n)(3n+2)/12\\$

Try it online!

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

```
{+/(¯1↓⍵)×1↓×⍨⍵}⍳

```

(Much longer) Port of Jonathan Allan's Jelly answer.

Try it online!

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

```
((×⍨+/)-(+/×⍨))⍳

```

Try it online!

```
 (×⍨+/)            The square (× self) of the sum (+ fold)
       -           minus
        (+/×⍨)     the sum of the square
(             )⍳   of [1, 2, … input].

```

# Answer
> 3 votes
# Mathematica, ~~21~~ 17 bytes

*-4 bytes thanks to alephalpha.*

```
(3#+2)(#^3-#)/12&

```

Pure function. Takes an integer as input and returns an integer as output. Just implements the polynomial, since `Sum`s, `Range`s, `Tr`s, etc. take up a lot of bytes.

# Answer
> 3 votes
# Java (JDK), 23 bytes

```
n->(3*n+2)*(n*n*n-n)/12

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
ÝDOnsnO-

```

Explanation:

```
ÝDOnsnO-     //Full program
Ý            //Push [0..a] where a is implicit input
 D           //Duplicate top of stack
  On         //Push sum, then square it
    s        //Swap top two elements of stack
     nO      //Square each element, then push sum
       -     //Difference (implicitly printed)

```

Try it online!

# Answer
> 3 votes
## C, C++, ~~46~~ ~~40~~ 37 bytes ( #define ), ~~50~~ ~~47~~ 46 bytes ( function )

-1 byte thanks to Zacharý

-11 bytes thanks to ceilingcat

Macro version :

```
#define F(n)n*n*~n*~n/4+n*~n*(n-~n)/6

```

Function version :

```
int f(int n){return~n*n*n*~n/4+n*~n*(n-~n)/6;}

```

Thoses lines are based on thoses 2 formulas :

Sum of numbers between 1 and n = `n*(n+1)/2`
Sum of squares between 1 and n = `n*(n+1)*(2n+1)/6`

So the formula to get the answer is simply `(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6`

And now to "optimize" the byte count, we break parenthesis and move stuff around, **while testing it always gives the same result**

`(n*(n+1)/2) * (n*(n+1)/2) - n*(n+1)*(2n+1)/6` =\> `n*(n+1)/2*n*(n+1)/2 - n*(n+1)*(2n+1)/6` =\> `n*(n+1)*n*(n+1)/4 - n*(n+1)*(2n+1)/6`

Notice the pattern `p = n*n+1 = n*n+n`, so in the function, we declare another variable `int p = n*n+n` and it gives :

`p*p/4 - p*(2n+1)/6`

For `p*(p/4-(2*n+1)/6)` and so `n*(n+1)*(n*(n+1)/4 - (2n+1)/6)`, it works half the time only, and I suspect integer division to be the cause ( `f(3)` giving 24 instead of 22, `f(24)` giving 85200 instead of 85100, so we can't factorize the macro's formula that way, even if mathematically it is the same.

Both the macro and function version are here because of macro substitution :

F(3) gives `3*3*(3+1)*(3+1)/4-3*(3+1)*(2*3+1)/6 = 22`
F(5-2) gives `5-2*5-2*(5-2+1)*(5-2+1)/4-5-2*(5-2+1)*(2*5-2+1)/6 = -30`

and mess up with the operator precedence. the function version does not have this problem

# Answer
> 3 votes
# MathGolf, 6 bytes

```
{î²ï*+

```

Try it online!

Calculates \\$\sum\_{k=1}^n (k^2(k-1))\\$

### Explanation:

```
{       Loop (implicit) input times
 î²     1-index of loop squared
    *   Multiplied by
   ï    The 0-index of the loop
     +  And add to the running total

```

# Answer
> 2 votes
# cQuents, ~~17~~ 15 bytes

```
b$)^2-c$
;$
;$$

```

Try it online!

## Explanation

```
 b$)^2-c$     First line
:             Implicit (output nth term in sequence)
 b$)          Each term in the sequence equals the second line at the current index
    ^2        squared
      -c$     minus the third line at the current index

;$            Second line - sum of integers up to n
;$$           Third line - sum of squares up to n

```

# Answer
> 2 votes
# JavaScript (ES6), 22 bytes

```
n=>n*~-n*-~n*(n/4+1/6)

```

Try it online!

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), ~~70~~ 69 bytes

```
 N =INPUT
I X =X + N ^ 3 - N ^ 2
 N =GT(N) N - 1 :S(I)
 OUTPUT =X
END

```

Try it online!

# Answer
> 2 votes
# Pyth, 7 bytes

```
sm**hdh

```

Try it online here.

Uses the formula in Neil's answer.

```
sm**hdhddQ   Implicit: Q=eval(input())
             Trailing ddQ inferred
 m       Q   Map [0-Q) as d, using:
    hd         Increment d
   *  hd       Multiply the above with another copy
  *     d      Multiply the above by d
s            Sum, implicit print

```

# Answer
> 2 votes
# Clojure, 58 bytes

```
(fn[s](-(Math/pow(reduce + s)2)(reduce +(map #(* % %)s))))

```

Try it online!

---

## Edit: I misunderstood the question

# Clojure, 55, 35 bytes

```
#(* %(+ 1 %)(- % 1)(+(* 3 %)2)1/12)

```

Try it online!

# Answer
> 2 votes
# Pari/GP, 21 bytes

```
n->(3*n+2)*(n^3-n)/12

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
LnDƶαO

```

Try it online!

**Explanation**

```
L         # push range [1 ... input]
 n        # square each
  D       # duplicate
   ƶ      # lift, multiply each by its 1-based index
    α     # element-wise absolute difference
     O    # sum

```

Some other versions at the same byte count:

`L<ān*O`
`Ln.āPO`
`L¦nā*O`

# Answer
> 2 votes
# , 28 bytes

```
x=1:scan();sum(x)^2-sum(x^2)

```

Try it online!

# Answer
> 2 votes
# MATLAB/Octave, 21 bytes

```
@(x)(x^3-x)*(x/4+1/6)

```

Anonymous function. We could save another 4 bytes if we assume `x` can be given as variable in workspace.
Implements \\$n(n−1)(n+1)(3n+2)/12\\$

---

One of my approaches was `@(x)-sum([sum(1:x)*i,1:x].^2)` which is few bytes longer but I found it interesting because It used imaginary unit to change the sign.
I also found out I can generate sum of squares by multiplying normal and transposed vector with `(1:x)*(1:x)'`. Might be useful for future challenges!

# Answer
> 2 votes
# Labyrinth, 20 bytes

```
?(:):):_3*(***_12/!@

```

Try it online!

Straightforward closed-form formula of \\$(x-1)x(x+1)(3x+2)/12\\$.

```
?      Take input [x]
(:):)  Decrement, dup, increment, dup, increment [x-1 x x+1]
:_3*(  Dup, 3 times, decrement [x-1 x x+1 3x+2]
***    Multiply four values
_12/   Divide by 12
!@     Print it and halt

```

# Labyrinth, 21 bytes

```
?
::(";;;!@
{  :
+**}

```

Try it online!

# Labyrinth, 22 bytes

```
   ?
:(::
}  "
**+{;!@

```

Try it online!

Two versions using a loop to evaluate \\$\sum\_{i=1}^{x}{i^2(i-1)}\\$. Both versions test the loop exit with `i-1 == 0`, discard the top values `;` as necessary, print the sum and exit.

```
?     Take input [x]; enter loop [sum i] with initial values of sum=0, i=x
::(   Dup, dup, decrement [sum i i i-1]
:}    Dup and move i-1 to aux. store [sum i i i-1 | i-1]
**+   Multiply top three values and add to sum [sum' | i-1]
{     Move i-1 back to the main stack

      Loop exit test can be done anywhere in the last iteration
      (i==1 or i==0), since that iteration does not affect the sum.

```

# Answer
> 2 votes
# ARM (Thumb), 18 bytes

```
.section .text
.global func
.thumb
// int func(int dummy, int x)
// returns sum(i*i*(i-1) for i in 1..x)
// r1 = i (x->1), r2 = i*i*(i-1), r0 = sum
func:
    mov r0, #0       // 2000   int sum = 0;
    mov r2, #0       // 2200   int prod = 0;
.loop:               //        do {
    add r0, r0, r2   // 1880   sum += prod;
    mov r2, r1       // 1c0a   prod = x;
    mul r2, r1       // 434a   prod *= x;
    sub r1, #1       // 3901   x -= 1;
    mul r2, r1       // 434a   prod *= x;
    bne .loop        // d1f9   } while (prod != 0);
    bx lr            // 4770   return sum;

```

A function that takes the input integer via `r1` and returns the value via `r0`.

Uses the iterative formula \\$\sum\_{i=1}^{x}{i^2(i-1)}\\$, iterating backwards. The loop terminates when the value of \\$i^2(i-1)\\$ is 0.

For the purposes of writing test cases, the C-side function signature takes a dummy value for `r0`.

Test cases written in C:

```
#include <stdio.h>

int func(int dummy, int x);
int main(void) {
    int dummy;
    int inputs[] = {1, 2, 3, 10, 24, 100};
    for(int i = 0; i < 6; ++i) {
        int v = inputs[i];
        printf("input = %d -> ans = %d\n", v, func(dummy, v));
    }
    return 0;
}

```

Build, run, objdump commands:

```
arm-linux-gnueabihf-gcc main_c.c func_c.S -static -o main_c
qemu-arm -L /usr/arm-linux-gnueabihf ./main_c
arm-linux-gnueabihf-objdump -d main_c | awk -v RS= '/^[[:xdigit:]]+ <(func|.loop)>/'

```

(The objdump + awk trick comes from this SO answer.)

# Answer
> 2 votes
# Vyxal, 8 bytes

```
ɾ∑²⁰ɾ²∑-

```

Try it Online!

literal solution, squares the sum and subtracts the sum of the squares.

# Answer
> 2 votes
# Factor \+ `math.unicode`, 32 bytes

```
[ [1,b] 3 dupn Σ sq -rot v. - ]

```

Try it online!

```
word   | data stack                                     | comment
-------+------------------------------------------------+--------------
       | 10                                             | example input
[1,b]  | { 1 2 ... 10 }                                 |
3      | { 1 2 ... 10 } 3                               |
dupn   | { 1 2 ... 10 } { 1 2 ... 10 } { 1 2 ... 10 }   |
Σ      | { 1 2 ... 10 } { 1 2 ... 10 } 55               | sum
sq     | { 1 2 ... 10 } { 1 2 ... 10 } 3025             | square
-rot   | 3025 { 1 2 ... 10 } { 1 2 ... 10 }             |
v.     | 3025 385                                       | dot product
-      | 2640                                           | output

```

# Answer
> 2 votes
# Fig, \\$9\log\_{256}(96)\approx\\$ 7.408 bytes

```
a
R@-mQJS

```

Try it online!

Port of 05AB1E. Literal solution is 2 chars longer.

```
a
R@-mQJS
-------
a       # Range [1, n]
------- # Use ^ as the input to the next line:
     JS # Prepend the sum to the list
   mQ   # Square each
R@      # Reduce by
  -     # Subtraction

```

# Answer
> 2 votes
# Julia 1.0, 20 bytes

Using the same formula as bigyihsuan:

```
~n=(n^3-n)*(3n+2)/12

```

Try it online!

---

Naive approach (34 bytes):
```
~n=(a=[1:n...];sum(a)^2-sum(a.^2))

```

Try it online!

# Answer
> 2 votes
# Excel, 21 bytes

```
=(A1^3-A1)*(A1/4+1/6)

```

This is the heartless Excel version of the formula figured out by others. There is also the 33 byte solution that feels a little more Excel-y:

```
=LET(n,SEQUENCE(A1),SUM(n^3-n^2))

```

... and the 38 byte solution that looks the most like the original formulas in the question:

```
=LET(n,SEQUENCE(A1),SUM(n)^2-SUMSQ(n))

```

# Answer
> 2 votes
# Husk, 11 8 bytes

```
-ṁ□ḣ¹□Σḣ

```

Try it online!

## Explanation

```
-ṁ□ḣ¹□Σḣ
-              Subtract
 ṁ□ḣ¹          The sum of the first n squares
     □         From the square of
      Σḣ       The sum from 1 to n

```

First time code golfing so this solution probably can be improved.

Thanks to Dominic van Essen for the -3 bytes.

# Answer
> 1 votes
# JAEL, ~~13~~ 10 bytes

```
#&àĝ&oȦ

```

Try it online!

## Explanation (generated automatically):

```
./jael --explain '#&àĝ&oȦ'
ORIGINAL CODE:  #&àĝ&oȦ

EXPANDING EXPLANATION:
à => `a
ĝ => ^g
Ȧ => .a!

EXPANDED CODE:  #&`a^g&o.a!

COMPLETED CODE: #&`a^g&o.a!,

#          ,            repeat (p1) times:
 &                              push number of iterations of this loop
  `                             push 1
   a                            push p1 + p2
    ^                           push 2
     g                          push p2 ^ p1
      &                         push number of iterations of this loop
       o                        push p1 * p2
        .                       push the value under the tape head
         a                      push p1 + p2
          !                     write p1 to the tapehead
            ␄           print machine state

```

# Answer
> 1 votes
# APL(NARS), 13 chars, 26 bytes

```
{+/⍵×⍵×⍵-1}∘⍳

```

use the formula Sum'w=1..n'(w*w*(w-1)) possible i wrote the same some other wrote + or - as "1⊥⍳×⍳×⍳-1"; test:

```
  g←{+/⍵×⍵×⍵-1}∘⍳
  g 0
0
  g 1
0
  g 2
4
  g 3
22
  g 10
2640

```

# Answer
> 1 votes
# Stax, 4 bytes

```
╡⌠(♠

```

Run and debug it

For all positive `k` integers up to the input, add `k^2 * (k-1)`.

# Answer
> 1 votes
# QBASIC, ~~45~~ 44 bytes

Going pure-math saves 1 byte!

```
INPUT n
?n^2*(n+1)*(n+1)/4-n*(n+1)*(2*n+1)/6

```

Try THAT online!

---

Previous, loop-based answer

```
INPUT n
FOR q=1TO n
a=a+q^2
b=b+q
NEXT
?b^2-a

```

Try it online!

Note that the REPL is a bit more expanded because the interpreter fails otherwise.

# Answer
> 1 votes
# PowerShell, ~~73~~ 39 bytes

```
1.."$args"|%{$r+=$_;$s+=$_*$_}
$r*$r-$s

```

Try it online!

-34 bytes thanks to @mazzy and his genius PowerShell-foo

# Answer
> 1 votes
# International Phonetic Esoteric Language, 21 bytes

```
ɪbwbbbffʍz3ʍf2sf{C}vo

```

Implements \\$(n^3-n)(3n+2)/12\\$.

Explanation:

```
ɪ       (input)
bw      (store n)
bbbffʍz (n^3-n)
3ʍf2s   (3n+2)
f       (multiply)
{C}v    (/12)
o       (print)

```

Testing against examples:

```
$ for i in 1 2 3 10 24 100; do echo {$i} | src/interpreter.py 'ɪbwbbbffʍz3ʍf2sf{C}vo'; done
0.0
4.0
22.0
2640.0
85100.0
25164150.0

```

# Answer
> 1 votes
# Flurry `-nii`, 32 bytes

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

```

Try it online!

Iterates through `k=0 .. n-1` using the stack height, adding `k(k+1)^2` each iteration.

### How it works

```
main = n add-next-term 0

// Initial height is 0
// Increase the height at (push height), so subsequent `height` calls give k+1
add-next-term = \x. x succ <(push height) height height>
= \x. x + k * (k+1) * (k+1)

```

# Answer
> 1 votes
# Arn, 9 bytes

```
└V0¯„○aÌ$

```

Try it!

# Explained

Unpacked: `+{^3-^2}\~`.

Performs \\$\large\sum\_{k=1}^{n}{(k^3-k^2)}\\$ where n is the input

```
          \       Fold with
+                 Addition
  {               After mapping with this block
        _         Implied variable (implicit index of block).
      ^           To the power of
        3         Literal three
    -             Minus
        _
      ^
        2         Literal two
  }               End block
            ~     1-range to
              _   Initialized to STDIN; implied

```

# Answer
> 1 votes
# Haskell, 22 bytes

```
f n=(3*n+2)*(n^3-n)/12

```

# Answer
> 1 votes
## Assembly (MIPS, SPIM), ~~142~~ 114 bytes, 6 * ~~12~~ 10 = ~~72~~ 60 assembled bytes

Saved 2 instructions (12 bytes) from @Bubbler's golf.

```
main:li$v0,5
syscall
li$a0,0
l:mul$t0,$v0,$v0
sub$v0,$v0,1
mul$t0,$t0,$v0
add$a0,$a0,$t0
bgtz$v0,l
li$v0,1
syscall

```

Try it online!

## Explanation

```
main:
    li $v0, 5              # Set syscall value 5
    syscall                # Syscall, v0 = input integer

    li $a0, 0              # a0 = 0

    loop:                  # Main loop (v0 is the counter):
        mul $t0, $v0, $v0  #     t0 = v0 * v0
        sub $v0, $v0, 1    #     v0 = v0 - 1
        mul $t0, $t0, $v0  #     t0 = t0 * v0
        add $a0, $a0, $t0  #     a0 = a0 + t0

        bgtz $v0, loop     #     if v0 > 0, jump to loop

    li $v0, 1              # Syscall value 1
    syscall                # Syscall (Output value of a0 as integer)

```

# Answer
> 1 votes
## Pip, 21 bytes

```
($+\,a)**2-$+(\,a)**2

```

My first self written pip answer!

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), ~~59~~ ~~48~~ 47 bytes

```
n=>(a=(x,b)=>x&&x*(b||x)+a(--x,b))(n,1)**2-a(n)

```

Try it online!

# Answer
> 1 votes
# C (gcc), 29 bytes

```
f(n){n=(3*n+2)*(n*n*n-n)/12;}

```

Try it online!

# Answer
> 1 votes
# , 15 bytes

```
(+/@:**:@>:)@i.

```

Uses the form \\$\sum\_{i=0}^{n-1}((i+1)^2\cdot i)\\$

Attempt This Online!

```
(+/@:**:@>:)@i.
             i. NB. range 0..n-1
            @   NB. atop f (g x)
(          )    NB. monadic hook, y f (g y)
      *:@>:     NB. increment then square
 +/@:*          NB. multiply square with each i then sum the result
                NB. u@:v where v is dyadic and u is always monadic,
                NB. like atop except u will execute once on the entire result

```

# Answer
> 1 votes
# Pip, ~~15~~ ~~13~~ 11 bytes

```
SQ_*D_MS\,a

```

Try It Online!

### Explanation

Adapted from one of the formulas in Engineer Toast's Excel answer:

$$ \sum\_{i=1}^{n} i^3-i^2 $$

which is equivalent to

$$ \sum\_{i=1}^{n} i^2(i-1) $$

```
SQ_*D_MS\,a
          a  Command-line argument
        \,   Inclusive range from 1
      MS     Map this function to each and sum the results:
SQ_            The argument squared
   *           Times
    D_         The argument decremented

```

---

Original 15-byte solution that implements the description directly:

```
\,:aSQ$+a-$+SQa

```

Try It Online!

# Answer
> 1 votes
# Vyxal, 7 bytes

```
ɾ:∑p²ƒ-

```

Try it Online!

A port of Fig which is a port of 05ab1e

## Explained

```
ɾ:∑p²ƒ-
ɾ:∑p     # prepend the sum of the range [1, n] to the range [1, n]
   ²ƒ-  # square everything and reduce by subtraction

```

# Answer
> 0 votes
## C#, 89 Bytes

```
int x=0,y=0;for(int i=1;i<=Int32.Parse(s[0]);i++){x+=i*i;y+=i;}Console.Write($"{y*y-x}");

```

ungolfed:

```
int x=0,y=0;
for(int i=1;i<=Int32.Parse(s[0]);i++){
x+=i*i;
y+=i;
}
Console.Write($"{y*y-x}");

```

Try it online!

# Answer
> 0 votes
# Axiom, 39 bytes

```
f(n)==reduce(+,[x^3-x^2 for x in 1..n])

```

test:

```
-> [[x,f x]for x in [1,2,3,10]]
     [[1,0],[2,4],[3,22],[10,2640]]

```

# Answer
> 0 votes
# Clojure, 91 bytes

```
(fn s[n](let[u #(apply + %)q #(Math/pow % 2)m(range 1(inc n))](-(q(u m))(u(map #(q %)m)))))

```

The naive, literal approach. See below:

```
(defn sum-sq-diff [n]
    (let [; Shortcut functions to save bytes
          sum #(apply + %)
          square #(Math/pow % 2)
          nums (range 1 (inc n))

          ss1 (sum (map #(square %) nums))
          ss2 (square (sum nums))]

      (- ss2 ss1)))

(mapv sum-sq-diff [1 2 3 10 24 100])
=> [0.0 4.0 22.0 2640.0 85100.0 2.516415E7]

```

Try it online!

# Answer
> 0 votes
# Ruby, 24 bytes

```
->n{(n+n+3*n*=n)*~-n/12}

```

Try it online!

# Answer
> 0 votes
# Python 3, 72 bytes

```
x=[i+1for i in range(int(input()))]
print(sum(x)**2-sum(i**2for i in x))

```

Try it online!

# Answer
> 0 votes
# F# (Mono), ~~57~~ 41 bytes

```
let f x=Seq.sumBy(fun y->y*y*(y-1))[1..x]

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
LDOšnÆ

```

Try it online!

Explanation:

```
           # implicit input (example: 3)
L          # range ([1, 2, 3])
 DOš       # prepend the sum ([6, 1, 2, 3])
    n      # square each ([36, 1, 4, 9])
     Æ     # reduce by subtraction (22)
           # implicit output

```

`Æ` isn't useful often, but this is its time to shine. This beats the naïve `LOnILnO-` by two whole bytes.

# Answer
> 0 votes
# PHP, 37 bytes

```
while($i<$argn)$s+=$i++*$i*$i;echo$s;

```

Try it online!

Standalone program input number via `STDIN`.

# Answer
> 0 votes
# Perl 6, 22 bytes

```
{($_³-$_)*($_/4+⅙)}

```

Try it online!

# Answer
> 0 votes
# Keg, 15 bytes

```
&⑻Ï⑷²⑸⅀⑻:⑨*½²$-

```

Try it online!

Calculates the sum of squares then the square of the sum.

# Answer
> 0 votes
# Whispers v2, 70 bytes

```
> 2
> Input
>> L³
>> L²
>> ∑ 1 2 3
>> ∑ 1 2 4
>> 5-6
>> Output 7

```

Try it online!

## How it works

Implements the formula

$$\sum^n\_{i=2}i^3 - \sum^n\_{i=2}i^2$$

As Whispers is difficult to deal with when it comes to compound statements inside of , `Each` etc. statements, it's actually shorter to calculate two sums and take their difference than it is to calculate

$$\sum^n\_{i=2}(i^3-i^2)$$

or any other single sum.

This has to be one of the easiest-to-read Whispers programs, aside from very trivial ones. We use the  statement to calculate the two sums, which works by taking the starting bound as the first value, the end bound second and finally the function to sum through last. Both of the  statements have the same bounds - \\$2\\$ and \\$n\\$ \- so the only thing that differs is the function. For the first  statement, we use the statement `>> L³` (i.e. cube), and `>> L²` (square) for the second. This yields the sums \\$\sum^n\_{i=2}i^3\\$ and \\$\sum^n\_{i=2}i^2\\$. Finally, we take their difference and output it.

# Whispers v3, 48 bytes

```
> 2
> Input
>>> L³-L²
>> ∑ 1 2 3
>> Output 4

```

With the introduction of pattern lines (starting with `>>>`) in version 3, compound statements in Whispers are much easier to deal with. Unfortunately, Whispers v3 is currently not available on TIO, so you'll have to use the interpreter in the Github repo.

This version takes advantage of pattern lines to shorten the code by only using one statement in the sum, rather than two separate sums. Other than that, it's fairly clear how it works, given the v2 program.

# Answer
> 0 votes
# 05AB1E, 11 bytes

```
LDOnU€nOXs-

```

Try it online!

```
             # (implicit) push STDIN to stack
LD           # push [1, 2, 3, ..., top of stack] twice
  OnU        # store squared sum of all values in top of stack in variable X
     €       # for each in top of stack...
      n      # push top of stack squared
       O     # push sum of all values in top of stack
        Xs-  # push X - top of stack
             # (implicit) output top of stack to STDOUT

```

# Answer
> 0 votes
# Thunno 2, 6 bytes

```
RDḣ²Ø.

```

Attempt This Online!

Port of Jonathan Allan's Jelly answer.

## Thunno 2, 8 bytes

```
RDS²s²S-

```

Attempt This Online!

Literal solution.

#### Explanation

```
RDḣ²Ø.  # Implicit input
R       # Push the range [1..input]
 D      # Duplicate it
  ḣ     # Remove the first item
   ²    # Square each number
    Ø.  # Dot product of the two lists
        # Implicit output

```

```
RDS²s²S-  # Implicit input
R         # Push the range [1..input]
 D        # Duplicate it
  S²      # Square the sum of the list
    s     # Swap so the range is back on top
     ²S   # Sum the squares of the numbers
       -  # Subtract
          # Implicit output

```

---
Tags: code-golf, math
---


title: Zeroes at the end of a factorial

text:
# Question
Title: Zeroes at the end of a factorial
Write a program or function that finds the number of zeroes at the end of `n!` in base 10, where `n` is an input number (in any desired format).

It can be assumed that `n` is a positive integer, meaning that `n!` is also an integer. There are no zeroes after a decimal point in `n!`. Also, it can be assumed that your programming language can handle the value of `n` and `n!`.

---

**Test cases**

```
1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461

```

This is code golf. Standard rules apply. The shortest code in bytes wins.

# Answer
> 45 votes
## Python 2, 27 bytes

```
f=lambda n:n and n/5+f(n/5)

```

The ending zeroes are limited by factors of 5. The number of multiples of `5` that are at most `n` is `n/5` (with floor division), but this doesn't count the repeated factors in multiples of `25, 125, ...`. To get those, divide `n` by 5 and recurse.

# Answer
> 21 votes
# Mornington Crescent, ~~1949 1909~~ 1873 bytes

```
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Parsons Green
Take District Line to Cannon Street
Take Circle Line to Victoria
Take Victoria Line to Seven Sisters
Take Victoria Line to Victoria
Take Circle Line to Victoria
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Hammersmith
Take District Line to Turnham Green
Take District Line to Bank
Take Circle Line to Hammersmith
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take Circle Line to Notting Hill Gate
Take Circle Line to Notting Hill Gate
Take Circle Line to Bank
Take Circle Line to Hammersmith
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Blackfriars
Take District Line to Upminster
Take District Line to Temple
Take Circle Line to Hammersmith
Take Circle Line to Cannon Street
Take Circle Line to Bank
Take Circle Line to Blackfriars
Take Circle Line to Hammersmith
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Cannon Street
Take District Line to Upney
Take District Line to Blackfriars
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Upminster
Take District Line to Upney
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Angel
Take Northern Line to Bank
Take Circle Line to Bank
Take District Line to Upminster
Take District Line to Bank
Take Circle Line to Bank
Take Northern Line to Mornington Crescent

```

Try it online!

-40 bytes thanks to NieDzejkob

-45 bytes thanks to Cloudy7

# Answer
> 19 votes
# Jelly, 5 bytes

```
!Æfċ5

```

Uses the counterproductive approach of finding the factorial then factorising it again, checking for the exponent of 5 in the prime factorisation.

Try it online!

```
!              Factorial
 Æf            List of prime factors, e.g. 120 -> [2, 2, 2, 3, 5]
   ċ5          Count number of 5s

```

# Answer
> 18 votes
## Pyth, 6 bytes

```
/P.!Q5

```

Try it here.

```
/    5   Count 5's in
 P        the prime factorization of
  .!Q      the factorial of the input.

```

Alternative 7-byte:

```
st.u/N5

```

The cumulative reduce `.u/N5` repeatedly floor-divides by `5` until it gets a repeat, which in this case happens after it hits 0.

```
34 -> [34, 6, 1, 0]

```

The first element is then removed (`t`) and the rest is summed (`s`).

# Answer
> 13 votes
## Actually, 10 bytes

```
!$R;≈$l@l-

```

Try it online!

Note that the last test case fails when running Seriously on CPython because `math.factorial` uses a C extension (which is limited to 64-bit integers). Running Seriously on PyPy works fine, though.

Explanation:

```
!$R;≈$l@l-
!           factorial of input
 $R         stringify, reverse
   ;≈$      make a copy, cast to int, then back to string (removes leading zeroes)
      l@l-  difference in lengths (the number of leading zeroes removed by the int conversion)

```

# Answer
> 11 votes
## Haskell, 26 bytes

```
f 0=0
f n=(+)=<<f$div n 5

```

Floor-divides the input by `5`, then adds the result to the function called on it. The expression `(+)=<<f` takes an input `x` and outputs `x+(f x)`.

Shortened from:

```
f 0=0
f n=div n 5+f(div n 5)

f 0=0
f n|k<-div n 5=k+f k

```

A non-recursive expression gave 28 bytes:

```
f n=sum[n`div`5^i|i<-[1..n]]

```

# Answer
> 8 votes
# MATL, 9 bytes

```
:"@Yf5=vs

```

**Try it online!**

This works for very large numbers, as it avoids computing the factorial.

Like other answers, this exploits the fact that the number of times `2` appears as divisor of the factorial is greater or equal than the number of times `5` appears.

```
:     % Implicit input. Inclusive range from 1 to that
"     % For each
  @   %   Push that value
  Yf  %   Array of prime factors
  5=  %   True for 5, false otherwise
  v   %   Concatenate vertically all stack contents
  s   %   Sum

```

# Answer
> 6 votes
## 05AB1E, 5 bytes

Would be 4 bytes if we could guarantee n\>4

**Code:**

```
Î!Ó7è

```

**Explanation:**

```
Î        # push 0 then input
  !      # factorial of n: 10 -> 2628800
   Ó     # get primefactor exponents -> [8, 4, 2, 1]
    7è   # get list[7] (list is indexed as string) -> 2
         # implicit output of number of 5s or 0 if n < 5

```

**Alternate, much faster, 6 byte solution:** Inspired by Luis Mendo's MATL answer

```
LÒ€`5QO

```

**Explanation:**

```
L         # push range(1,n) inclusive, n=10 -> [1,2,3,4,5,6,7,8,9,10]
 Ò        # push prime factors of each number in list -> [[], [2], [3], [2, 2], [5], [2, 3], [7], [2, 2, 2], [3, 3], [2, 5]]
  €`      # flatten list of lists to list [2, 3, 2, 2, 5, 2, 3, 7, 2, 2, 2, 3, 3, 2, 5]
    5Q    # and compare each number to 5 -> [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
      O   # sum -> 2

```

**Edit:** removed solutions using **¢** (count) as all primes containing 5 would be counted as 5 e.g. 53.

**Edit 2:** added a more efficient solution for higher input as comparison.

# Answer
> 6 votes
## Matlab  ***~~(59) (54)~~***(39)

Hey dawg !!!! we heard you like maths ....

```
  @(n)sum(fix(n./5.^(1:fix(log(n)/1.6))))

```
* This is based on my created answer in code review.
* further than what is mentioned in my answer in code review, the formula for number of zeros in factorial(n) is Sum(n/(5^k)) where k varies between 1 and log\_5(n)
* The only trivial reason why it cant get golfier is that `log5` isnt available in matlab as a builtin , thus I replaced log(5) by 1.6, doesnt matter because it will be anyways floored.

Give it a try

# Answer
> 5 votes
# Julia, ~~34~~ ~~31~~ 30 bytes

```
n->find(digits(prod(1:n)))[]-1

```

This is an anonymous function that accepts any signed integer type and returns an integer. To call it, assign it to a variable. The larger test cases require passing `n` as a larger type, such as a `BigInt`.

We compute the factorial of `n` (manually using `prod` is shorter than the built-in `factorial`), get an array of its `digits` in reverse order, `find` the indices of the nonzero elements, get the first such index, and subtract 1.

Try it online! (includes all but the last test case because the last takes too long)

Saved a byte thanks to Dennis!

# Answer
> 5 votes
# Mathematica, 20 bytes

```
IntegerExponent[#!]&

```

`IntegerExponent` counts the zeros. For fun, here's a version that doesn't calculate the factorial:

```
Tr[#~IntegerExponent~5&~Array~#]&

```

# Answer
> 5 votes
# C, 28 bytes

```
f(n){return(n/=5)?n+f(n):n;}

```

## Explanation

The number of trailing zeros is equal to the number of fives that make up the factorial. Of all the `1..n`, one-fifth of them contribute a five, so we start with `n/5`. Of these `n/5`, a fifth are multiples of 25, so contribute an extra five, and so on. We end up with `f(n) = n/5 + n/25 + n/125 + ...`, which is `f(n) = n/5 + f(n/5)`. We do need to terminate the recursion when `n` reaches zero; also we take advantage of the sequence point at `?:` to divide `n` before the addition.

As a bonus, this code is much faster than that which visits each `1..n` (and much, much faster than computing the factorial).

## Test program

```
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char **argv) {
    while(*++argv) {
        int i = atoi(*argv);
        printf("%d: %d\n",i,f(i));
    }
}

```

## Test output

> 1: 0
> 4: 0
> 5: 1
> 24: 4
> 25: 6
> 124: 28
> 125: 31
> 666: 165
> 2016: 502
> 2147483644: 536870901
> 2147483647: 536870902

# Answer
> 4 votes
# JavaScript ES6, 20 bytes

```
f=x=>x&&x/5+f(x/5)|0

```

Same tactic as in xnor's answer, but shorter.

# Answer
> 4 votes
# C, 36

```
r;f(n){for(r=0;n/=5;)r+=n;return r;}

```

Same method as @xnor's answer of counting 5s, but just using a simple for loop instead of recursion.

Ideone.

# Answer
> 4 votes
# Jelly, 3 bytes

```
!ọ5

```

Try it online!

## How it works

```
!ọ5 - Main link. Takes n on the left
!   - Yield n!
 ọ5 - How many times is it divisible by 5?

```

# Answer
> 3 votes
# Retina, 33 bytes

Takes input in unary.

Returns output in unary.

```
+`^(?=1)(1{5})*1*
$#1$*1;$#1$*
;

```

(Note the trailing linefeed.)

Try it online!

## How it works:

### The first stage:

```
+`^(?=1)(1{5})*1*
$#1$*1;$#1$*

```

Slightly ungolfed:

```
+`^(?=1)(11111)*1*\b
$#1$*1;$#1$*1

```

What it does:

* Firstly, find the greatest number of `11111` that can be matched.
* Replace by that number
* Effectively floor-divides by `5`.
* The lookahead `(?=1)` assures that the number is positive.
* The `+`` means repeat until idempotent.
* So, the first stage is "repeated floor-division by 5"

If the input is 100 (in unary), then the text is now:

```
;;1111;11111111111111111111

```

### Second stage:

```
;

```

Just removes all semi-colons.

# Answer
> 2 votes
# Ruby, 22 bytes

One of the few times where the Ruby `0` being truthy is a problem for byte count.

```
f=->n{n>0?f[n/=5]+n:0}

```

# Answer
> 2 votes
# Perl 6, 23 bytes

```
{[+] -$_,$_,*div 5…0}
{sum -$_,$_,*div 5...0}

```

I could get it shorter if `^...` was added to Perl 6 `{sum $_,*div 5^...0}`.
It should be more memory efficient for larger numbers if you added a `lazy` modifier between `sum` and the sequence generator.

### Explanation:

```
{ # implicitly uses $_ as its parameter
  sum

    # produce a sequence
    -$_,     # negate the next value
     $_,     # start of the sequence

     * div 5 # Whatever lambda that floor divides its input by 5

             # the input being the previous value in the sequence,
             # and the result gets appended to the sequence

     ...     # continue to do that until:

     0       # it reaches 0
}

```

### Test:

```
#! /usr/bin/env perl6

use v6.c;
use Test;

my @test = (
     1,   0,
     5,   1,
   100,  24,
   666, 165,
  2016, 502,
  1234567891011121314151617181920,
        308641972752780328537904295461,

  # [*] 5 xx 100
  7888609052210118054117285652827862296732064351090230047702789306640625,
        1972152263052529513529321413206965574183016087772557511925697326660156,
);

plan @test / 2;

# make it a postfix operator, because why not
my &postfix:<!0> = {[+] -$_,$_,*div 5...0}

for @test -> $input, $expected {
  is $input!0, $expected, "$input => $expected"
}

diag "runs in {now - INIT now} seconds"

```

```
1..7
ok 1 - 1 => 0
ok 2 - 5 => 1
ok 3 - 100 => 24
ok 4 - 666 => 165
ok 5 - 2016 => 502
ok 6 - 1234567891011121314151617181920 => 308641972752780328537904295461
ok 7 - 7888609052210118054117285652827862296732064351090230047702789306640625 => 1972152263052529513529321413206965574183016087772557511925697326660156
# runs in 0.0252692 seconds

```

( That last line is slightly misleading, as MoarVM has to start, load the Perl 6 compiler and runtime, compile the code, and run it. So it actually takes about a second and a half in total.
That is still significantly faster than it was to check the result of the last test with WolframAlpha.com )

# Answer
> 2 votes
# Mathcad, \[tbd\] bytes

Mathcad is sort of mathematical "whiteboard" that allows 2D entry of expressions, text and plots. It uses mathematical symbols for many operations, such as summation, differentiation and integration. Programming operators are special symbols, usually entered as single keyboard combinations of control and/or shift on a standard key.

What you see above is exactly how the Mathcad worksheet looks as it is typed in and as Mathcad evaluates it. For example, changing n from 2016 to any other value will cause Mathcad to update the result from 502 to whatever the new value is.

http://www.ptc.com/engineering-math-software/mathcad/free-download

---

Mathcad's byte equivalence scoring method is yet to be determined. Taking a symbol equivalence, the solution takes about 24 "bytes" (the while operator can only be entered using the "ctl-\]" key combination (or from a toolbar)). Agawa001's Matlab method takes about 37 bytes when translated into Mathcad (the summation operator is entered by ctl-shft-$).

# Answer
> 2 votes
# dc, 12 bytes

```
[5/dd0<f+]sf

```

This defines a function `f` which consumes its input from top of stack, and leaves its output at top of stack. See my C answer for the mathematical basis. We repeatedly divide by 5, accumulating the values on the stack, then add all the results:

```
5/d   # divide by 5, and leave a copy behind
d0<   # still greater than zero?
f+    # if so, apply f to the new value and add

```

## Test program

```
# read input values
?
# print prefix
[  # for each value
    # print prefix
    [> ]ndn[ ==> ]n
    # call f(n)
    lfx
    # print suffix
    n[
]n
    # repeat for each value on stack
    z0<t
]
# define and run test function 't'
dstx

```

## Test output

```
./79762.dc <<<'1234567891011121314151617181920 2016 666 125 124 25 24 5 4 1'

```

```
1 ==> 0
4 ==> 0
5 ==> 1
24 ==> 4
25 ==> 6
124 ==> 28
125 ==> 31
666 ==> 165
2016 ==> 502
1234567891011121314151617181920 ==> 308641972752780328537904295461

```

# Answer
> 2 votes
# Julia, ~~21~~ 19 bytes

```
!n=n<5?0:!(n÷=5)+n

```

Uses the recursive formula from xnor's answer.

Try it online!

# Answer
> 2 votes
# Vyxal `s`, 5 bytes

```
ɾǐƛ5O  # main program

```

```
ɾ      # range over input
 ǐ     # take the prime factors of each number
  ƛ5O  # for each value, count the 5s
-s     # sum top of stack

```

Try it Online!

# Vyxal, 3 bytes

```
¡5Ǒ

```

This one uses the same approach as caird coinheringaahing's answer

Try it Online!

# Vyxal `l`, 3 bytes (for inputs \> 4)

```
¡Ġt

```

Approach by Lyxal, takes the factorial of the input, groups by consecutive, then gets the length of the tail using the -l flag.

Try it Online!

# Answer
> 2 votes
# asm2bf, 32 bytes

```
@f
divr1,5
addr2,r1
jnzr1,%f
ret

```

Resulting brainfuck code (~500 bytes):

```
+>+[<[>-]>[>]>+<<<[>>>[-]<-<<-]+>>+[-<[>+>-<<-]>>[<<<->>[<+
>>+<-]>[-]]<[-]]<<[>>+<<-]>>[-<<+>>>>>>>>>+++++[>>>>+<<<<-]
<<<<[>>>>>>>+>-[>>]<[[>+<-]<+>>>]<<<<<<<<<-]>>>>>>[<<<<<<+>
>>>>>-]>[<<<+>>>-]>[<<<<+>>>>-]<<<<[-]<<<<[>+<<+>-]<[>+<-]>
>>>>+<<<<[<<<<<[-]>>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>
>>>>+<<<<<<<-]>>>[<<<+>>>-]]<<<[>>>+<<<-]>>>>>>>[-]<<<<<<<]
<<[>>+<<-]>>[-<<+[-]>[-]>>>>>>>>>>>>>>>>>>>>>[>>]<<->[<<<[<
<]<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>[>>]>-]<<<[<<]<<
<<<<<<<<<[-]<<<<<<<]<<[>>+<<-]>>[-<<+>>]<]

```

### Extras

If you want to test the algorithm, you can use the following driver code. The code expects `r1` to be the input number and leaves the output in `r2`, assuming `r2` is already cleared:

```
movr1,666
@f
divr1,5
addr2,r1
jnzr1,%f
outr1

```

The resulting value might be outputted as an ASCII character, so you might have to use `bfi fac.b | xxd` to see the numerical value.

### Optimizing for brainfuck source code size

We can optimize the code a fair bit. Since brainfuck has no notion of procedures, we can assume that `@f` is a while loop label (instead of being both a function and a normal label) and that we don't have to return.

The `jnz` instruction and the accompanying label can be replaced with a sequence of `nav r1 / raw .[` or `.]`. To top it off, we use the `-t` flag for bfmake. The result:

```
>>>[>>>>+++++[>>>>+<<<<-]<<<<[>>>>>>>+>-[>>]<[[>+<-]<+>>>]<<<<<<<<<-]>>>>>>[<<<<<<+>>>>>>-]>[<<<+>>>-]>[<<<<+>>>>-]<<<<[-]<<<<[>+<<+>-]<[>+<-]>]

```

... at 144 bytes.

# Answer
> 2 votes
# Excel, 25 bytes

```
=SUM(INT(A9/5^ROW(1:99)))

```

Calculates the number of 5s in the prime factorization. In theory, it would work for all of the examples above, except Excel can't handle numbers as long as the last one with the correct precision.

# Answer
> 1 votes
## Python 3, 52 bytes

```
g=lambda x,y=1,z=0:z-x if y>x else g(x,y*5,z+x//y)

```

# Answer
> 1 votes
# J, ~~28~~ ~~17~~ 16 bytes

```
<.@+/@(%5^>:@i.)

```

Pretty much the same as the non-recursive technique from xnor's answer.

---

Here's an older version I have kept here because I personally like it more, clocking in at 28 bytes:

```
+/@>@{:@(0<;._1@,'0'&=@":@!)

```

Whilst not needed, I have included `x:` in the test cases for extended precision.

```
   tf0 =: +/@>@{:@(0<;._1@,'0'&=@":@!@x:)
   tf0 5
1
   tf0 100
24

   tf0g =: tf0"0
   tf0g 1 5 100 666 2016
0 1 24 165 502

```

The last number doesn't work with this function.

## Explanation

This works by calculating `n!`, converting it to a string, and checking each member for equality with `'0'`. For `n = 15`, this process would be:

```
15
15! => 1307674368000
": 1307674368000 => '1307674368000'
'0' = '1307674368000' => 0 0 1 0 0 0 0 0 0 0 1 1 1

```

Now, we use `;._1` to split the list on its first element (zero), boxing each split result, yielding a box filled with aces (`a:`) or runs of `1`s, like so:

```
┌┬─┬┬┬┬┬┬┬─────┐
││1│││││││1 1 1│
└┴─┴┴┴┴┴┴┴─────┘

```

We simple obtain the last member (`{:`), unbox it (`>`), and perform a summation over it `+/`, yielding the number of zeroes.

Here is the more readable version:

```
split =: <;._1@,
tostr =: ":
is =: =
last =: {:
unbox =: >
sum =: +/
precision =: x:
n =: 15

NB. the function itself
tf0 =: sum unbox last 0 split '0' is tostr ! precision n
tf0 =: sum @ unbox @ last @ (0 split '0'&is @ tostr @ ! @ precision)
tf0 =: +/ @ > @ {: @ (0 <;._1@, '0'&= @ ": @ ! )

```

# Answer
> 1 votes
# Jolf, 13 bytes

```
Ώmf?H+γ/H5ΏγH

```

Defines a recursive function which is called on the input. Try it here!

```
Ώmf?H+γ/H5ΏγH  Ώ(H) = floor(H ? (γ = H/5) + Ώ(γ) : H)
Ώ              Ώ(H) =
       /H5                           H/5
      γ                         (γ =    )
     +    Ώγ                              + Ώ(γ)
   ?H       H               H ?                  : H
 mf                   floor(                        )
               // called implicitly with input

```

# Answer
> 1 votes
# Dyalog APL, 9 bytes

```
⊥⍨'0'=⍕!⎕

```

prompt for number

`!` factorialize

stringify

`'0'=` check equality to character zero

`⊥⍨` count trailing trues\*

---

\*Literally it is a mixed-base to base-10 conversion, using the boolean list as both number and base:

`⊥⍨0 1 0 1 1` is the same as `0 1 0 1 1⊥⍨0 1 0 1 1` which is `0×(0×1×0×1×1) 1×(1×0×1×1) 0×(0×1×1) 1×(1×1) + 1×(1)` which again is two (the number of trailing 1s).

# Answer
> 1 votes
## Perl, ~~24~~ 22 + 1 (`-p` flag) = 23 bytes

```
$\+=$_=$_/5|0while$_}{

```

Using:

```
> echo 2016 | perl -pe '$\+=$_=$_/5|0while$_}{'

```

Full program:

```
while (<>) {
# code above added by -p
    while ($_) {
        $\ += $_ = int($_ / 5);
    }
} {
# code below added by -p
    print;  # prints $_ (undef here) and $\
}

```

# Answer
> 1 votes
## Pyke, 5 bytes

```
SBP5/

```

Try it here!

```
S     -    range(1,input()+1)
 B    -   product(^)
  P   -  prime_factors(^)
   5/ - count(^, 5)

```

# Answer
> 1 votes
# Haskell, 39 bytes

Can't compete with `@xnor`, but it was fun and the result is a different approach:

```
f n=sum$[1..n]>>= \i->1<$[5^i,2*5^i..n]

```

# Answer
> 1 votes
# RETURN, 17 bytes

```
[$[5÷\%$F+][]?]=F

```

`Try it here.`

Recursive operator lambda. Usage:

```
[$[5÷\%$F+][]?]=F666F

```

# Explanation

```
[             ]=F  Lambda -> Operator F
 $                 Check if top of stack is truthy
  [       ][]?     Conditional
   5÷\%$F+         If so, do x/5+F(x/5)

```

# Answer
> 1 votes
# Ruby, ~~70~~ ~~61~~ ~~51~~ 49 bytes

**Version 3** with thanks to Kenny Lau and daniero

```
->n{(n-n.to_s(5).chars.map(&:to_i).reduce(:+))/4}

```

**Edit:** Turns out you can save two bytes by mapping `to_i` *before* you `reduce`. Weird :P

This function subtracts the sum of `n`'s base 5 digits from `n` and then divides that result by 4. This is related to the sum of the geometric series `1+5+25+..+5**n = (5**n+1)/4`.

As an example (again, with thanks to Kenny Lau), consider `358` (`2413` in base 5) minus its base 5 digits.

```
2413-2-4-1-3
= (2000-2) + (400-4) + (10-1) + (3-3)
# consider that 1000-1=444 and you'll see why every 5**n is multiplied by 4
= 2*444 + 4*44 + 1*4 + 3*0
= 2*(4*5**0+4*5**1+4*5**2) + 4*(4*5**0+4*5**1) + 1*(4*5**0) + 3*()
= 348

```

Divide `348` by `4` and you get `f(358) = 87`.

**Version 2** with thanks to Kenny Lau

```
->n{s=(1..n).reduce(:*).to_s;s.size-s.reverse.to_i.to_s.size}

```

This function calculates `n!` then subtracts the `size` of `n!` from the `size` of `(n!).reverse.to_i.to_s`, which removes all the zeroes, thus, returning the `size` of the zeroes themselves.

**Version 1**

```
->n{s=n.to_s(5).chars;(0...s.size).reduce{|a,b|a+(s[0,b]*'').to_i(5)}}

```

This a variation of the "How many `5`s are there in the prime factorization of `n!`?" trick that uses Ruby's simple base conversion builtins.

The golfing is a bit of a pain though, with converting from `Integer` to `String` to `Array`, grabbing part of the `Array` and converting that to `String` to `Integer` again for the `reduce`. Any golfing suggestions are welcome.

# Answer
> 1 votes
# Java, 38 bytes

```
int z(int n){return n>0?n/5+z(n/5):0;}

```

## Full program, with ungolfed method:

```
import java.util.Scanner;

public class Q79762{
    int zero_ungolfed(int number){
        if(number == 0){
            return 0;
        }
        return number/5 + zero_ungolfed(number/5);
    }
    int z(int n){return n>0?n/5+z(n/5):0;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();
        System.out.println(new Q79762().zero_ungolfed(n));
        System.out.println(new Q79762().z(n));
    }
}

```

# Answer
> 1 votes
# J, 7 bytes

Monadic function, taking argument on the right.

```
3{:@q:!

```

If `x` is positive, `x q: y` returns the exponents in a prime factorization of `y`, for only the first `x` primes. The `3`-rd prime is 5 and `{:` takes the tail of a list.

Note that you have to input integers with an `x` at the end, or else J will treat them as floats.

```
   3{:@q:! 100x
24
   3{:@q:! 666x
165
   3{:@q:! 2016x
502

```

Try it yourself at tryj.tk, though be warned that this online interpreter will complain if you try anything larger than 1343.

If you want something that doesn't compute *n*! and hence doesn't require it fit in an integer, use the recursive solution `<.@%&5(+$:@)^:*`. (tryj.tk is still whiny on large inputs.)

# Answer
> 1 votes
# Pyt, 5 bytes

```
5←!ḋɔ

```

Explanation:

```
5             Pushes 5
 ←            Gets input
  !           Factorial
   ḋ          Prime factors (with duplicates)
    ɔ         Count occurrences of 5 in the list of prime factors

```

Try it online!

# Answer
> 1 votes
# J, 15 bytes

```
+/<.(%5:^>:@i.)

```

Who needs to calculate factorial?

Probably longer than with though :p

Explanation when I get home

# Answer
> 1 votes
# Runic Enchantments, 21 bytes

```
Rl1)?@+
/:>i5,'fA:0)?

```

Try it online!

Uses the same `f(n) = n/5 + f(n/5)` as other answers. Just took some coercion to to reduce the footprint as much as possible. Fortunately `>` does nothing when executed (it simply marks the entry point) and `i` pushes nothing to the stack when no more input remains.

# Answer
> 1 votes
# Python 2, 33 bytes

```
f=lambda n:n/5+f(n/5)if n>0else 0

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 4 bytes

```
!Ò5¢

```

Try it online!

```
!Ò5¢  # full program
   ¢  # number of...
  5   # literal...
   ¢  # s in...
 Ò    # prime factorization of...
!     # factorial of...
      # implicit input
      # implicit output

```

# Answer
> 1 votes
# Thunno 2, 4 bytes

```
wf5c

```

Attempt This Online!

#### Explanation

```
wf5c  # Implicit input  ->  10
w     # Factorial       ->  3628800
 f    # Prime factors   ->  [2,2,2,2,2,2,2,2,3,3,3,3,5,5,7]
  5c  # Count 5s        ->  2
      # Implicit output

```

# Answer
> 0 votes
# CJam, 9 bytes

```
l~m!mf5e=

```

Try it online!

Just counting the 5's `5e=` in the prime factorization `mf` of the factorial `m!` of the input `l~`.

Doesn't work for big factorials, since they don't fit into an integer.

# Answer
> 0 votes
# C, 53 bytes

```
 i,r;z(n){for(;i=n--;)for(;i=i%5?0:i/5;)r++;return r;}

```

Counting 5s in the sequence that makes up the factorial, instead of calculating the factorial and then counting its 5s.

Full program:

```
i,r;z(n){for(;i=n--;)for(;i=i%5?0:i/5;)r++;return r;}
#include <stdio.h>
int main(int argc, char **argv) {
    int n;
    sscanf(argv[1], "%d", &n);
    printf("%d -> %d\n", n, z(n));
    return 0;
}

```

# Answer
> 0 votes
## Convex, 6 bytes

```
¡mf5e=

```

Use Java interpreter or this alternate version that works on TIO: Try it online

This would be 4 bytes if I was finished getting rid of 2 char operators....

# Answer
> 0 votes
## PowerShell v2+, 60 bytes (but see the NB below)

A completely different approach, doing exactly what is requested by the challenge. ;-)

```
$a=2..$args[0]-join'*'|iex;"$a".length-"$a".Trim('0').length

```

Takes input `$args` and creates a dynamic range `..`, then `-join`s it together with `*` for multiplication, pipes that to `iex` (similar to `eval`) to compute the factorial. Store that in `$a`.

We then take the length of the string representation and subtract off the length of the string representation after we've passed it to `.Trim('0')` which will remove leading and trailing zeroes. Since there will never be leading zeroes, this gets us the result we want.

**NB:** The above will work for up to `n=17` without a problem, as even though `17!` is bigger than `[Int]::MaxValue`, since we didn't explicitly specify the casting for `$a`, PowerShell will dynamically convert it to `[double]` for us upon overflow. Yeah ... in PowerShell, `[int]` will overflow to `[double]` if not explicitly cast. No, I don't know why it goes to that rather than `[int64]`.

However, at `18!`, PowerShell will automatically convert the number to scientific notation when the implicit `.ToString()` is called (i.e., when encapsulating it within quotes), in order to preserve significant digits. We can get around that with explicit formatting instead -- `$a="{0:0}"-f(2..$args[0]-join'*'|iex);$a.length-$a.Trim('0').length` -- at **67 bytes**. That will get us up to `20!` before we start to run into loss of precision.

Thus, to handle an "arbitrary" input, we'll need to combine the above explicit formatting with the `[bigint]` datatype ...

### PowerShell v2+, 80 bytes

```
$a="{0:0}"-f("[bigint]"+(2..$args[0]-join'*')|iex);$a.length-$a.Trim('0').length

```

This will prepend an explicit cast of `[bigint]` to the first number in the range `2`, and in PowerShell the datatype on the left of the operator is used for output, so that `[bigint]` datatype will continue through the rest of the factorial calculation.

---

An few examples of the three methods at some key points, with some additional output text showing what's happening in the background -- the first output is the top code, the middle is with the explicit string formatting, and the bottom is with the `[bigint]` datatype.

```
PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 17
(Normal) 355687428096000 = 3
(Format) 355687428096000 = 3
(BigInt) 355687428096000 = 3

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 18
(Normal) 6.402373705728E+15 = 0
(Format) 6402373705728000 = 3
(BigInt) 6402373705728000 = 3

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 21
(Normal) 5.10909421717094E+19 = 0
(Format) 51090942171709400000 = 5
(BigInt) 51090942171709440000 = 4

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 100
(Normal) 9.33262154439441E+157 = 0
(Format) 933262154439441000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000 = 143
(BigInt) 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000
00000000 = 24

PS C:\Tools\Scripts> .\golfing\zeroes-at-end-of-factorial.ps1 666
(Normal) Infinity = 0
(Format) Infinity = 0
(BigInt) 101063205684078149339082270812987645175758239832414541134042080735741380210369702298920280680149101204098980220355752703933970405713072930283454242384
016585642874066153029797241068282869939717688434251350949378748077490349338925526287834176188326189942648494465716169313138031111761957305152642332038964180541
081606760789306748325981681536460982866866274811038560365797328460484207809414155642770874534510059882948847250594907196772727091196506088520929434066550648022
642608335790150309778114083249701373807911277761571911620331754219999948922714475266708579675248268885046126373228453917614236582397369676453760327876932228670
885547506983568164371084614056976933006577541441308350104365957229945444651724282400214055514046429629100190143841467573055296491456926973403850076414055114364
283612861330473414734808609512385966092678846067118146921625221337465049955783174195059482714722569989641408869425126104519667256749553222882671938160611697400
311264211156133257350321296072971178199390387741639438171846476552757501425212904028323696392262434445697502405816736843180906854457725847298397943781807264821
360865009874936976105696120379126536366566469680224519996204004154443821032721047698220334845859609307929656956126740947391412413210205581149373619966878853487
232170536051130524871079644147921335454258357607659625021345466796883799602327316306909470042946710666392541958119313633986054565867362395523193239940480940410
876723200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000 = 165

```

# Answer
> 0 votes
# dc, 26

```
?[5/dd0<m]dsmx[+z1<m]dsmxp

```

# Answer
> 0 votes
# rs, 95 bytes

```
(\d+)/(_)^^(\1)
_(_+)/_\1 \1
+_(_+) _(_+)$/(_\1)^^((^^_\2)) \2
 _$/
(_+)/(^^\1)
.*?(0*)$/(^^\1)

```

Live demo.

Note that I can't test this with large inputs such as 100. Feel free to try it, but you'd need over 8.486e145 TB of RAM...

An explanation of the first 5 lines is available here. The last line just counts the zeroes at the end.

# Answer
> 0 votes
# CJam, 11

Efficient solution, similar to other answers.

## Loop version:

```
ri{5/_}h]:+

```

Try it online

**Explanation:**

```
ri      read the input and convert to integer
{…}h    do…while
  5/    divide by 5
  _     duplicate the last number
         the loop terminates when the number reaches 0
]:+     add all the numbers from the stack

```

## Recursive version:

```
ri0{5/_j+}j

```

Try it online

**Explanation:**

```
ri       read the input and convert to integer
0{…}j    calculate with memoized recursion and initial value 0 for input 0
  5/     divide by 5
  _      duplicate the result
  j      calculate the number of zeros recursively for that number
  +      add the 2 results

```

# Answer
> 0 votes
# PHP, 62 bytes

```
for($n=$z=0;++$n<=log(125,5);){$z+=floor(125/(5**$n));}echo$z;

```
**exploded view**
```
for ($n=$z=0; ++$n<=log(125,5); ) {
  $z += floor( 125 / (5 ** $n) );
}
echo $z;

```

The starting point for many of the answers here is that every 5th factor adds a single 0, since there are 2-3 even numbers that precede it, and you can only get a new 0 with both a factor of 2 and a factor of 5.

If we assumed this to be true, the answer is simple in PHP, in 23 bytes:

```
echo(floor(argv[0]/5));

```

**However,** consider `25!`. `24!` has 4 0's in it (because of 5, 10, 15, and 20). But 25 adds **two** 5's to the equation, meaning `25!` has **6** 0's in it. So we have to account for `5^n` as well.

# Answer
> 0 votes
# GNU coreutils, 34 bytes

```
seq $1|factor|tr \  \\n|grep -cx 5

```

The set of prime factors of the factorial `n!` is the union of the sets of prime factors of `1..n`. We just need to count the number of fives, as this will always be less than the number of twos, and it takes one five and one two to produce each trailing zero. Happily, `n==0` correctly produces 0, even though the question doesn't require that.

The output of `factor` is not quite what we want (in fact, in every golf I do, the reprinting of input is a nuisance):

```
$ seq 6|factor
1:
2: 2
3: 3
4: 2 2
5: 5
6: 2 3

```

By replacing each space with a newline, we can match lines that are exactly `5` (this handily eliminates the `5:` prefix for that line), and count the total.

You will probably run out of memory and/or time trying the last of the example inputs, but there's nothing in the program itself that wouldn't work.

# Answer
> 0 votes
# bc, 51 bytes

```
define f(x){if(x){return x/5+f(x/5)}else{return 0}}

```

Same tactic as in xnor and Cᴏɴᴏʀ O'Bʀɪᴇɴ's answers, but longer.

# Answer
> 0 votes
# Erlang, 33 bytes

```
f(0)->0;f(N)->N div 5+f(N div 5).

```

Same tactic as in xnor and Cᴏɴᴏʀ O'Bʀɪᴇɴ's answers.

Ungolfed:

```
f(0) -> 0;
f(N) when N > 0 -> N div 5 + f(N div 5).

```

# Answer
> 0 votes
# GML, 35 bytes

```
a=argument0 while a/=5b+=a return b

```

# Answer
> 0 votes
# Japt, 6 bytes

Can only handle inputs up to 21 due to JavaScript's integer limitations.

```
Êk xv5

```

Try it

---

## Explanation

```
Ê          :Factorial
 k         :Prime factors
   v5      :Divisible by 5?
  x        :Reduce by addition

```

# Answer
> 0 votes
# PHP, ~~43~~ 39 bytes

based on Toby Speight´s C solution

```
function f($n){return$n?f($n/=5)+$n|0:0;}

```

Try it online.

# Answer
> 0 votes
# Stax, 4 bytes

```
╩+Pî

```

Run and debug it

I omitted the final test case. The algorithm is correct, but the time requirements are beyond my patience or predicted lifespan.

## Method:

1. Compute factorial
2. Calculate "multiplicity" by 10.

# Answer
> 0 votes
# Forth (gforth), 38 bytes

Based on Toby Speight's C Solution

```
: f dup 0> if 5 / dup recurse + then ;

```

Try it online!

### Code Explanation

```
: f           \ start a new word definition
  dup 0> if   \ check if n > 0
    5 / dup   \ divide by 5 and duplicate if so
    recurse   \ call f on n/5
    +         \ add to sum
  then        \ end if
;             \ end word definition

```

# Answer
> 0 votes
# Keg, `-rR`, 9 bytes

```
0&¡÷{0=|⑹

```

Try it online!

I'm sure there is a more efficient way by using some sort of formula, but a counting method was the best I could think of.

## Explained

```
0&¡÷{0=|⑹
0&          #Store 0 in the register
  ¡÷        #Take the factorial of the (implicit) input and item split
    {0=     #While the top item is still 0:
       |⑹  #    Increment the register
            #-rR prints the register as an integer at end of execution

```

# Answer
> 0 votes
# naz, 10 bytes

```
1r3s5d9s1o

```

Try it online!

The maximum factorial that naz *could* technically store is \\$5!\\$ (120), so being allowed to assume that \\$n!\\$ will fit within our language's integer type paves the way for a very boring answer.

We first read \\$n\\$ from the input string, which sets the register to \\$n\\$'s ASCII value \\$k\\$. The number of zeroes at the end of \\$n!\\$ is then given by:

$$\lfloor(k - 3) / 5\rfloor - 9$$

The only value of \\$k\\$ that will result in a value of \\$1\\$ is \\$53\\$, which corresponds to \\$n = 5\\$.

# Answer
> 0 votes
# Lua, 48 bytes

```
function u(x)return x>0 and x//5+u(x//5)or 0 end

```

Try it online!

# Answer
> 0 votes
# AWK, 34 bytes

```
{i=$0;for($0=0;i;)$0+=i=int(i/5)}1

```

Ungolfed:

```
{i=$0;for($0=0;i;)$0+=i=int(i/5)}1
{                               }   for each line
 i=$0;                                save it in i
          $0=0;                       set output to 0
      for(     i;)                    while i is nonzero
                        int(i/5)        divide i by 5 without reminder
                      i=                save the result in i
                  $0+=                  and add it to output
                                 1    print output

```

Try it online!

# Answer
> 0 votes
# Risky, 6 bytes

```
!!?+_0__/\\?

```

Try it online!

## Explanation

```
! length
!       factorial
?         input
+     +
_
0         0
_   apply function
_
/         5
\     find indices in
\       prime factors
?         argument

```

---
Tags: code-golf, math, factorial
---