title: Lowest digit addition generator

text:
# Question
Title: Lowest digit addition generator
A *digit addition generator* of an integer `n` is any integer `x` that satisfy the equation `x + s(x) = n`, with `s(x)` being the sum of the digits of `x`. (We will work under base 10 for convenience.)

For example, a digit addition generator for `29` would be `19`, because `19 + (1 + 9) = 29`. Some numbers have more than one generator. An example might be `216`, which has generators of `198` and `207`.

Your objective is to generate the sequence `a_n` where `a_i` is the **lowest** digit addition generator of every non-negative integer `i`, and *anything other than a non-negative integer* if there is none for `i`. The non-negative terms in your result should match the sequence A096234. You may find this paper related to the challenge.

Fewest bytes win; standard rules apply.

# Answer
> 5 votes
# 05AB1E, 7 bytes

```
Ý.ΔDªOQ

```

Outputs `-1` if there is no result.

Try it online or verify a few more test cases.

**Explanation:**

```
Ý        # Push a list in the range [0, (implicit) input-integer]
 .Δ      # Find the first value of this list that's truthy for, or -1 if none are:
   D     #  Duplicate the current value
    ª    #  Convert the first value to a list of digits,
         #  and append the duplicated number to this list
     O   #  Sum the list together
      Q  #  Check whether it's equal to the (implicit) input-integer
         # (after which the result is output implicitly)

```

# Answer
> 5 votes
# Vyxal `gM`, 28 bitsv2, 3.5 bytes

```
'∑+?=

```

Try it Online!

Outputs an empty list for no result. I think (spoiler I did) I ninja'd someone in the process of writing this lol.

## Explained

```
'∑+?=
'      # filter the range [0, n] by:
 ∑+    #   sum of digits + x
   ?=  #   equals input?
# g flag prints minimum.

```

# Answer
> 4 votes
# Japt, 8 bytes

Outputs `-1` for no result.

```
ôÈ+ìxÃbU

```

Try it

(Eventually) outputs `undefined` for no result.

```
@¶X+ìx}a

```

Try it

```
ôÈ+ìxÃbU     :Implicit input of integer U
ô            :Range [0,U]
 È           :Pass each through the following function
  +          :  Add
   ì         :  Convert to digit array
    x        :  Reduce by addition
     Ã       :End function
      bU     :First 0-based index of U

```

```
@¶X+ìx}a     :Implicit input of integer U
@            :Function taking an integer X as argument
 ¶           :  Test U for equality with
  X+         :    Add to X
    ì        :      Convert X to digit array
     x       :      Reduce by addition
      }      :End function
       a     :Get the first integer >=0 that returns true

```

# Answer
> 4 votes
# PARI/GP, 44 bytes

```
f(n,i)=if(i>n,x,i+sumdigits(i)-n,f(n,i+1),i)

```

Attempt This Online!

Returns `x` when there is no solution.

# Answer
> 4 votes
# APL (Dyalog Extended), 21 bytes

Anoymous tacit prefix function. Requires 0-indexing (`⎕IO←0`).

```
⍸⊢<\⍤=0,⍨⍳+1⊥¨⍎¨∘⍕¨∘⍳

```

Try it online!

where do we find that

the argument

`<\` is the first (lit. cum. right-ass. less red.)

that:

`=` equals

`0,⍨` zero appended to

the range

`+` plus

`1⊥` the sum (lit. base-1 eval.)

`¨` of each of

the evaluation

`¨` of each

of:

the stringification

`¨` of each

of:

the range

# Answer
> 4 votes
# C (clang), 58 bytes

*loops forever if there's no solution*

```
d,s;f(*i,n){for(*i=s=0;n-s;)for(s=d=++*i;d;d/=10)s+=d%10;}

```

Try it online!

# C (clang), 70 bytes

For comparison, this returns negative values when there's no solution.

```
g,o,l;f(*i,n){for(*i=g=-n;g++;*i=n+l?*i:-g)for(l=o=g;o;o/=10)l+=o%10;}

```

Try it online!

# Answer
> 4 votes
# C++ (gcc), ~~71~~ \\$\cdots\\$ ~~66~~ 64 bytes

```
[](int&n){for(int m=n,d=n=0,t;m-d;)for(d=t=++n;t;t/=10)d+=t%10;}

```

Try it online!

*Saved 6 bytes thanks to c--!!!*

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~89~~ ~~53~~ ~~49~~ 44 bytes

```
#&@@Pick[r=Range@#,r+Tr/@IntegerDigits@r,#]&

```

Try it online!

Thanks to @ovs and @att!

# Answer
> 3 votes
# Arturo,  ~~40~~  35 bytes

```
$->x[0while[x<>+∑digits<=<=]->1+]

```

Try it!

Causes an infinite loop when there is no result.

```
$->x[                  ; a function taking an integer x
    0                  ; push 0 to stack
    while[x<>          ; while x doesn't equal...
        <=<=           ; duplicate top of stack twice
        +∑digits       ; digit sum then add
    ]                  ; end while condition
    ->1+               ; increment top of stack (while body)
]                      ; end function

```

# Answer
> 3 votes
# JavaScript, 49 bytes

Loops forever, in theory, if there's no result but, in practice, throws a recursion error.

```
n=>(g=x=>n-eval([x,...x+``].join`+`)?g(++x):x)`0`

```

Try it online!

# Answer
> 3 votes
# , ~~45~~ 46 bytes

*Edit: +1 byte to correctly handle input of zero, but then -1 byte thanks pajonk for removal of useless accidental space*

```
\(n){while(n-F-sum(F%/%10^(0:F)%%10))F=F+1;+F}

```

Attempt This Online!

Tests increasing integers until it finds a solution, so loops forever if no solution exists.

# Answer
> 3 votes
# Pyth, 8 bytes

```
x|msajdT

```

Try it online!

Returns `-1` for no result.

### Explanation

```
x|msajdTdQQQ    # implicitly add dQQQ
                # implicitly assign Q = eval(input())
  m      Q      # map lambda d over range(Q):
     jdT        #   list the digits of d
    a   d       #   append d to this list
   s            #   sum the list
 |        Q     # short circuiting or, does nothing unless the input is 0, then [] -> 0
x          Q    # find the first index of Q in the mapped list (or xors with 0 for 0), returns -1 if not found

```

# Answer
> 3 votes
# Raku, 34 bytes

```
{first 0..$^n: {$_+.comb.sum==$n}}

```

Try it online!

Returns the `first` element of the range `0` through the input number `$^n`/`$n` such that the element `$_` plus the sum of its digits `.comb.sum` is equal to the input number. If there is no such number, `Nil` is returned.

# Answer
> 3 votes
# Julia, ~~42~~ 37 bytes

```
~n=argmax(x->x+sum(digits(x))==n,0:n)

```

Attempt This Online!

-5 bytes thanks to MarcMush: use `argmax` instead of `findfirst`

# Answer
> 3 votes
# Elixir, 74 72 bytes

```
import Enum
c=& &1-?0
r=&find(1..&1,fn x->&1==x+sum map'#{x}',c end)||-1

```

Try it online!

# Answer
> 2 votes
# Java, 85 bytes

```
n->{for(int i=-1;i++<n;)if((i+"").chars().map(d->d-48).sum()+i==n)return i;return-1;}

```

Outputs `-1` if there is no result.

Try it online.

**Explanation:**

```
n->{                   // Method with integer as both parameter and return-type
  for(int i=-1;i++<n;) //  Loop `i` in the range (-1,n]:
    if((i+"")          //   Convert `i` to a String
       .chars()        //   Then to an IntStream of codepoints
       .map(d->d-48)   //   Then to an IntStream of digits
       .sum()          //   And sum those digits together
             +i        //   Add integer `i`
               ==n)    //   And if it's equal to input `n`:
      return i;        //    Return `i` as result
  return-1;}           //  If no result is found, return `-1` instead

```

Using a recursive function which throws a `StackOverflowError` when there is no result is also **85 bytes**:

```
n->f(n,0)int f(int n,int i){return(i+"").chars().map(d->d-48).sum()+i==n?i:f(n,i+1);}

```

Try it online.

# Answer
> 2 votes
# Charcoal, 13 bytes

```
ＮθＩ⌊Φ⊕θ⁼θ⁺ιΣι

```

Try it online! Link is to verbose version of code. Takes `i` as an input and outputs `None` if no generator exists. Explanation: Brute force approach.

```
Ｎθ              First input as an integer
      θ         First input
     ⊕          Incremented
    Φ           Filter on implicit range
          ι     Current value
         ⁺      Plus
            ι   Current value
           Σ    Digit sum
       ⁼        Equals
        θ       First input
   ⌊            Take the minimum
  Ｉ             Cast to string
                Implicitly print

```

23 bytes for a less inefficient version:

```
ＮθＩ⌊Φ…·⁻θ×⁹Ｌθθ⁼θ⁺ιΣ⌈⟦⁰ι

```

Try it online! Link is to verbose version of code. Explanation: Starts checking for generators starting from `i` minus `9` times the number of digits of `i`.

28 bytes for a more efficient version:

```
ＮθＩ⌊ΦＥＬθ⁻⁻θ﹪×⁵θ⁹×⁹ι⁼θ⁺ιΣ⌈⟦⁰ι

```

Try it online! Link is to verbose version of code. Explanation: As above, but only checks for generators which when doubled are equivalent to `i` modulo `9` (because `i` equals the generator plus its digit sum but both the generator and the digit sum are equivalent modulo `9`) although it actually computes the maximum possible generator by subtracting `5i` reduced modulo `9` from `i`.

# Answer
> 2 votes
# C# (.NET Core), 73 72 bytes

```
n=>{for(int i=-1;i++<n;)if((i+"").Sum(d=>d-'0')+i==n)return i;return-1;}

```

Try it online!

This is a C# port of this answer. All the kudos goes to Kevin Cruijssen.

I really like that .NET's `sum` is taking a lambda to avoid the common map followed by sum!

# Answer
> 2 votes
# Python 3, 63 bytes

```
g=lambda n:min(x for x in range(n)if x+sum(map(int,str(x)))==n)

```

Try it online!

# Answer
> 2 votes
# Python 3, 56 bytes

```
f=lambda n,o=0:(o+sum(map(int,str(o)))==n)*o or f(n,o+1)

```

Try it online!

# Answer
> 1 votes
# Fig, \\$11\log\_{256}(96)\approx\\$ 9.054 bytes

```
[KFax'=#x+S

```

Try it online!

```
[            # The first item from
   a         # the range from 1 to
    x        # the input,
  F  '       # filtered by:
          S  #   the digit sum of n
         +   #   plus n
      =      #   is equal to
       #x    #   the program's input,
 K           # sorted (smallest to largest).

```

# Answer
> 1 votes
# Swift, ~~84~~  80 bytes

```
{n in(0...n).map{($0,"\($0)".reduce($0){$0+$1.hexDigitValue!})}.first{$1==n}!.0}

```

Takes an `Int` in and returns an `Int`.

Try it online!

Ungolfed:

```
{ (n: Int) -> Int in
  (0...n) // a sequence of all integers from 0 to n, inclusive
    // the parens are needed to avoid parsing as 0...(n.map)
    .map { i in // transform each one
      ( // return a tuple of:
        i, // 0. the integer itself
        "\(i)".reduce(i) { $0 + $1.hexDigitValue! } // 1. the digit sum plus the number
        // technically, wholeNumberValue would be more correct than hexDigitValue
      )
    }
    .first { $1 == n }! // find the first one where the sum is the input
    .0 // and return the number that gave that sum
}

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=sum -pa`, 29 bytes

```
$_=0;$_++while"@F"-sum$_,/./g

```

Try it online!

# Answer
> 1 votes
# Desmos, 66 bytes

```
I=[0...n]
f(n)=I[[i+∑_{k=0}^imod(floor(i/10^k),10)fori=I]=n].min

```

Returns `undefined` if no solution exists.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 1 votes
# Ruby, 46 bytes

```
1.step{|c|p (1..c).find{|x|x+x.digits.sum==c}}

```

Try it online!

# Answer
> 1 votes
# Thunno 2 `M`, 5 bytes

```
æDS+=

```

Attempt This Online!

#### Explanation

```
æDS+=  # Implicit input
æ      # Filter [1..input] by:
 D     #  Duplicate
  S    #  Sum digits
   +   #  Add
    =  #  Equals input?
       # Take the minimum
       # Implicit output

```

# Answer
> 0 votes
# Haskell, 52 bytes

```
a n=find((==n).ap(+)(sum.map digitToInt.show))[1..n]

```

Try it online!

# Answer
> 0 votes
# Scala, 71 bytes

Try it online!

```
n=>(0 to n).find(i=>(i.toString.map(_.asDigit).sum+i)==n).getOrElse(-1)

```

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


title: Square-free semiprime counting

text:
# Question
Title: Square-free semiprime counting
## Definition

> A square-free semiprime is a natural number that is the product of two distinct prime numbers.

## The task

Given a natural number `n`, count all square-free semiprimes less than or equal to `n`.

## Details

Please write a function or procedure that accepts a single integer parameter and counts all square-free semiprimes less than or equal to its parameter. The count must either be a return value of a function call or be printed to STDOUT.

## Scoring

The answer with the fewest number of characters wins.

In the event of a tie, the following criteria will be used in order:

1. Tallest person
2. Best
3. Worst

## Examples

```
f(1)     = 0
f(62)    = 18
f(420)   = 124
f(10000) = 2600

```

# Answer
## J, 50 40 38 37 characters

```
f=:3 :'+/y<:}.~.,(~:/**/)~p:i._1&p:y'

```

Usage:

```
   f 1
0
   f 62
18
   f 420
124
   f 10000
2600

```

With thanks to FUZxxl.

**Performance test**

```
   showtotal_jpm_ ''[f 1[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000046│0.000046│100.0│100 │1  │
│[total]│      │        │0.000046│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000095│0.000095│100.0│100 │2  │
│[total]│      │        │0.000095│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.000383│0.000383│100.0│100 │3  │
│[total]│      │        │0.000383│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │0.084847│0.084847│100.0│100 │4  │
│[total]│      │        │0.084847│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘
   showtotal_jpm_ ''[f 1[f 62[f 420[f 10000[f 50000[start_jpm_ ''
 Time (seconds)
┌───────┬──────┬────────┬────────┬─────┬────┬───┐
│name   │locale│all     │here    │here%│cum%│rep│
├───────┼──────┼────────┼────────┼─────┼────┼───┤
│f      │base  │5.014691│5.014691│100.0│100 │5  │
│[total]│      │        │5.014691│100.0│100 │   │
└───────┴──────┴────────┴────────┴─────┴────┴───┘

```

I'm no theoretician as has been seen here in the past, but I think the time complexity is something like O(np2) where np is the number of primes up to and including the input number n. This is based on the assumption that the complexity of my method (generating a very large multiplication table) far outweighs the complexity of the prime generating function built in to J.

**Explanation**

`f=:3 :'...'` declares a (monadic) verb (function). The input to the verb is represented by `y` within the verb definition.

`p:i._1&p:y` The `p:` verb is the multi purpose primes verb, and it's used in two different ways here: `_1&p:y` returns the number of primes less than `y` then `p:i.` generates every one of them. Using 10 as input:

```
   p:i._1&p:10
2 3 5 7

```

`(~:/**/)~` generates the table I spoke of earlier. `*/` generates a multiplication table, `~:/` generates a not-equal table (to eliminate the squares) and both of these are multiplied together. Using our previous output as input:

```
   */~2 3 5 7
 4  6 10 14
 6  9 15 21
10 15 25 35
14 21 35 49

   ~:/~2 3 5 7
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

   (~:/**/)~2 3 5 7
 0  6 10 14
 6  0 15 21
10 15  0 35
14 21 35  0

```

`}.~.,` now we turn the numbers into one list `,` get the unique values `~.` and remove the 0 at the start `}.`

```
   }.~.,(~:/**/)~2 3 5 7
6 10 14 15 21 35

```

`y<:` a comparison with the original input to check which values are valid:

```
   10<:6 10 14 15 21 35
1 1 0 0 0 0

```

`+/` and then sum that to get the answer.

```
   +/1 1 0 0 0 0
2

```
> 7 votes

# Answer
# Mathematica 65 64 55 51 47 39

**Code**

The following counts the number of square-free semiprimes less than or equal to `n`:

```
FactorInteger@Range@n~Count~{a={_,1},a}

```

Any square-free semiprime factors into a structure of the form: `{{p,1}{q,1}}` For example,

```
FactorInteger@221
(* out *)
{{13, 1},{17, 1}}

```

The routine simply counts the numbers in the desired range that have this structure of factors.

---

**Usage**

```
n=62;
FactorInteger@Range@n~Count~{a={_,1},a}

(* out *)
18

```

---

**Timing: All the given examples**

```
FactorInteger@Range@#~Count~{a = {_, 1}, a} & /@ {1, 62, 420, 10^4} // Timing

(* out *)
{0.038278, {0, 18, 124, 2600}}

```

---

**Timing: n=10^6**

It takes under four seconds to count the number of square-free semi-primes less than or equal to one million.

```
n=10^6;
FactorInteger@Range@n~Count~{a = {_, 1}, a}//Timing
(* out *)
{3.65167, 209867}

```
> 5 votes

# Answer
## Python, 115

```
r=range
p=lambda x:all(x%i for i in r(2,x))
f=lambda x:sum([i*j<=x and p(j)and p(i)for i in r(2,x)for j in r(2,i)])

```
> 4 votes

# Answer
# Jelly, 7 bytes

```
ŒcfÆf€L

```

Try it online!

### How it works

```
ŒcfÆf€L  Main link. Argument: n

Œc       Generate all 2-combinations of [1, ..., n], i.e., all pairs [a, b] such
         that 1 ≤ a < b ≤ n.
   Æf€   Compute the prime factorization of each k in [1, ..., n].
  f      Filter; keep only results that appear to the left and to the right.
      L  Take the length.

```
> 4 votes

# Answer
## Python (139)

```
from itertools import*;s=lambda n:sum(x*y<=n and x<y for x,y in product(filter(lambda x:all(x%i for i in range(2,x)),range(2,n)),repeat=2))

```

Please provide some sample results so competitors could test their programs.
> 3 votes

# Answer
## Ruby 82

```
z=->n{[*2..n].select{|r|(2...r).all?{|m|r%m>0}}.combination(2).count{|a,b|a*b<=n}}

```

Demo: http://ideone.com/cnm1Z
> 3 votes

# Answer
# Python 139

```
def f(n):
 p=[];c=0
 for i in range(2,n+1):
    if all(i%x for x in p):p+=[i]
    c+=any((0,j)[i/j<j]for j in p if i%j==0 and i/j in p)
 return c

```
> 2 votes

# Answer
## Golfscript 64

```
~:ß,{:§,{)§\%!},,2=},0+:©{©{1$}%\;2/}%{+}*{..~=\~*ß>+\0?)+!},,2/

```

Online demo here

***Note:** In the demo above I excluded the `420` and `10000` test cases. Due to the extremely inefficient primality test, it's not possible to get the program to execute for these inputs in less than 5 seconds.*
> 2 votes

# Answer
## Shell, 40

```
#!/bin/sh

seq $1|factor|awk 'NF==3&&$2!=$3'|wc -l

#old, 61
#seq $1|factor|awk 'BEGIN{a=0}NF==3&&$2!=$3{a++}END{print a}'

```

Usage:

```
$ ./count 1
0
$ ./count 420
124
$ ./count 10000
2600
$ time ./cnt.sh 1000000
209867

real    0m23.956s
user    0m23.601s
sys     0m0.404s

```
> 2 votes

# Answer
# Jelly, 14 13 bytes

```
RÆEḟ0⁼1,1$Ɗ€S

```

Try it online!

```
RÆEḟ0⁼1,1$Ɗ€S    main function:
RÆE             get the prime factorization Exponents on each of the Range from 1 to N,
          Ɗ€    apply the preceding 1-arg function composition (3 funcs in a row) to each of the prime factorizations:
                (the function is a monadic semiprime checker, as per DavidC's algorithm)
    ḟ0          check if the factors minus the zero exponents...
      ⁼1,1$      ...are equal to the list [1,1]
             S   take the Sum of those results, or number of successes!

```

Constructive criticism welcomed!
> 2 votes

# Answer
# Python 2/3, ~~95~~ 94 bytes

```
lambda n:sum(map(F,range(n+1)))
F=lambda x,v=2:sum(x%i<1and(F(i,0)or 3)for i in range(2,x))==v

```

Try it online!

Posted in a 6 year old challenge because it sets a new Python record, an IMO it's a pretty interesting approach.

# Explanation

```
lambda n:sum(map(F,range(n+1)))           # Main function, maps `F` ("is it a semiprime?")
                                          #  over the range [0, n]
F=lambda x,v=2:                           # Helper function; "Does `x` factor into `v`
                                          #  distinct prime numbers smaller than itself?"
  sum(                                    # Sum over all numbers `i` smaller than `x`
    x%i<1                                 # If `i` divides `x`,
    and                                   #  then
    (F(i,0)                               #  add 1 if `i` is prime (note that `F(i,0)`
                                          #  is just a primality test for `i`!)
    or 3)                                 #  or `3` if `i` is not prime (to make `F`
                                          #  return `False`)
  for i in range(2,x))
  ==v                                     # Check if there were exactly `v` distinct prime
                                          #  factors smaller than `x`, each with
                                          #  multiplicity 1

```

# Python 2/3 (PyPy), ~~88~~ ~~82~~ 81 bytes

```
lambda n:sum(sum(x%i<1and(x/i%i>0or 9)for i in range(2,x))==2for x in range(n+1))

```

Try it online!

Based on a 92-byte golf by Value Ink. PyPy is needed to correctly interpret `0or`, because standard Python sees this as an attempt at an octal number.
> 2 votes

# Answer
# Pari/GP, 61 bytes

Golfed version. Try it online!

```
f(n)={c=0;forprime(p=2,sqrtint(n),forprime(q=p+1,n/p,c++));c}

```

Ungolfed version. Try it online!

```
squareFreeSemiPrimes(n) = {
    local(count = 0);
    forprime(p = 2, sqrtint(n),
        forprime(q = p+1, n/p,
            count++
        )
    );
    return(count);
}
\\ Here is an example of how to call the function
print(squareFreeSemiPrimes(1))
print(squareFreeSemiPrimes(62))
print(squareFreeSemiPrimes(420))
print(squareFreeSemiPrimes(10000))

```
> 2 votes

# Answer
# Perl 6, ~~58~~ 45 bytes

*Thanks to Jo King for -13 bytes.*

```
{+grep {3==.grep($_%%*)&&.all³-$_}o^*,1..$_}

```

Takes advantage of the fact that integers with four factors are either square-free semiprimes or perfect cubes.

Try it online!
> 1 votes

# Answer
# Stax, 8 bytes

```
ßº@N¬Që↔

```

Run and debug it

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

```
F       for 1..n run the rest of the program
  :F    get distinct prime factors
  2(    trim/pad factor list to length 2
  :*    compute product of list
  _/    integer divide by initial number (yielding 0 or 1)
  +     add to running total

```

Run this one
> 1 votes

# Answer
# Brachylog, 7 bytes

```
{≥ḋĊ≠}ᶜ

```

Try it online!

```
           The output is
{    }ᶜ    the number of ways in which you could
 ≥         choose a number less than or equal to
           the input
  ḋ        such that its prime factorization
   Ċ       is length 2
    ≠      with no duplicates.

```
> 1 votes

# Answer
# Retina, 58 bytes

```
_
¶_$`
%(`$
$"
,,`_(?=(__+)¶\1+$)
¶1$'
)C`1(?!(__+)\1+¶)
2

```

Try it online!

Takes as input unary with `_` as tally mark

## Explanation

A number is a square-free semi-prime if its largest and smallest factor, excluding itself and 1, are both primes.

```
_
¶_$`

```

Takes the input and generate each unary number less than or equal to it, each on its own line

```
%(`

```

Then, for each number ...

```
$
$"
,,`_(?=(__+)¶\1+$)
¶1$'

```

Find its smallest and largest factor, excluding itself an 1 ...

```
)C`1(?!(__+)\1+¶)

```

and count the number of them that is prime. Since the smallest factor must be a prime, this returns 1 or 2

```
2

```

Count the total number of 2's
> 0 votes

# Answer
# Python 2, ~~105~~ 104 bytes

```
lambda m:sum(reduce(lambda(a,v),p:(v*(a+(n%p<1)),v>0<n%p**2),range(2,n),(0,1))[0]==2for n in range(m+1))

```

Try it online!

1 byte thx to squid
> 0 votes

# Answer
# APL(NARS), chars 26, bytes 52

```
{≢b/⍨{(⍵≡∪⍵)∧2=≢⍵}¨b←π¨⍳⍵}

```

test:

```
  f←{≢b/⍨{(⍵≡∪⍵)∧2=≢⍵}¨b←π¨⍳⍵}
  f 1
0
  f 9
1
  f 62
18
  f 420
124
  f 1000
288
  f 10000
2600
  f 100000
23313

```

this is a longer alternative (59 chars that i would prefer)

```
r←h w;n;t
n←4⋄r←0
n+←1⋄→0×⍳w<n⋄→2×⍳(2≠≢t)∨2≠≢∪t←πn⋄r+←1⋄→2

```

test:

```
  h 1000000
209867

```
> 0 votes

# Answer
# Ruby `-rprime`, 64 bytes

I know that there's another Ruby solution here, but I didn't want to bump it with comments since it was answered in 2012... and as it turns out, using a program flag counts it as a different language, so I guess this technically isn't "Ruby" anyhow.

Try it online!

**Explanation**

```
->n{(1..n).count{|i|m=i.prime_division;m.size|m.sum(&:last)==2}}
->n{                                    # Anonymous lambda
    (1..n).count{|i|                    # Count all from 1 to `n` that match
                                        # the following condition
                m=i.prime_division;     # Get the prime factors of `i` as
                                        #  base-exponent pairs (e.g. [2,3])
                m.size                  # Size of factors (# of distinct primes)
                      |                 # bit-or with...
                       m.sum(&:last)    # Sum of the last elements in the pairs
                                        #  (the sum of the exponents)
                                    ==2 # Check if that equals 2 and return.
                                        # Because 2 is 0b10, the bit-or means
                                        #  that the condition is true iff both
                                        #  are either 2 or 0, but because this
                                        #  is a prime factorization, it is
                                        #  impossible to have the number of
                                        #  distinct primes or the sum of the
                                        #  exponents to equal 0 for any number
                                        #  > 1. (And for 1, size|sum == 0.)
    }                                   # End count block
}                                       # End lambda

```
> 0 votes

---
Tags: code-golf, primes, fastest-code, counting
---


title: Factorial digit sum

text:
# Question
Title: Factorial digit sum
## The challenge is to calculate the digit sum of the factorial of a number.

---

Example

```
Input: 10
Output: 27

```

10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27

You can expect the input to be an integer above 0. Output can be of any type, but the answer should be in the standard base of the coding language.

---

Test cases:

```
10    27
19    45
469   4140
985   10053

```

N.B. Some languages can not support large numbers above 32-bit integers; for those languages you will not be expected to calculate large factorials.

OEIS link here thanks to Martin Ender

---

This is , so shortest code in characters wins!

# Answer
> 14 votes
# 05AB1E, 3 bytes

```
!SO

```

Try it online!

```
!   Factorial.
 S  Push characters separately.
  O Sum.

```

# Answer
> 11 votes
## Jelly, 3 bytes

```
!DS

```

Try it online!

Does what you expect:

```
!    Factorial.
 D   Decimal digits.
  S  Sum.

```

# Answer
> 8 votes
## Mathematica, 21 bytes

```
Tr@IntegerDigits[#!]&

```

# Answer
> 8 votes
# C++11, 58 bytes

As unnamed lambda modifying its input:

```
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}

```

One of the rare cases when my C++ code is shorter than the C code.

If you want to suppport larger cases, switch to **C++14** and use:

```
[](auto&n){auto i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}

```

and supply the calling argument with `ull` suffix.

Usage:

```
auto f=
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
;

main() {
  int n=10;
  f(n);
  printf("%d\n",n);
}

```

# Answer
> 7 votes
## Ruby, ~~63~~ ~~61~~ ~~53~~ 38 bytes

New approach thanks to manatwork:

```
->n{eval"#{(1..n).reduce:*}".chars*?+}

```

Old:

```
->n{(1..n).reduce(:*).to_s.chars.map(&:hex).reduce:+}

```
* -3 bytes thanks to Martin Ender
* -5 bytes thanks to G B

# Answer
> 6 votes
# Pyth, ~~7~~ 6 bytes

*Thanks to @Kade for saving me a byte*

`sj.!QT`

Try it online!

This is my first time using Pyth, so I'm sure that my answer could be golfed quite a bit.

Explanation:

```
s Sum
  j the digits of
    .! the factorial of
      Q the input
    T in base 10

```

# Answer
> 5 votes
## Haskell, ~~41~~ 40 bytes

```
f x=sum$read.pure<$>(show$product[1..x])

```

Usage example: `f 985` -\> `10053`.

Make a list from `1`to `x`, calculate the product of the list elements, turn it into its string representation, turn each character into a number and sum them.

Edit: @Angs saved a byte. Thanks!

# Answer
> 5 votes
# Python, 54 bytes

```
f=lambda n,r=1:n and f(n-1,r*n)or sum(map(int,str(r)))

```

**repl.it**

# Answer
> 5 votes
## R, 58 53 bytes

Edit: Saved one byte thanks to @Jonathan Carroll and a couple thanks to @Micky T

```
sum(as.double(el(strsplit(c(prod(1:scan()),""),""))))

```

Unfortunately, with 32-bit integers, this only works for `n < 22`. Takes input from stdin and outputs to stdout.

If one would like higher level precision, one would have to use some external library such as `Rmpfr`:

```
sum(as.numeric(el(strsplit(paste(factorial(Rmpfr::mpfr(scan()))),""))))

```

# Answer
> 4 votes
# Pip, 8 bytes

```
$+$*++,a

```

Try it online!

**Explanation**

```
      ,a    # range
    ++      # increment
  $*        # fold multiplication
$+          # fold sum

```

# Answer
> 4 votes
## CJam, 8 bytes

```
rim!Ab:+

```

Try it online!

### Explanation

```
r   e# Read input.
i   e# Convert to integer.
m!  e# Take factorial.
Ab  e# Get decimal digits.
:+  e# Sum.

```

# Answer
> 4 votes
# APL (Dyalog Extended), 8 bytes

-3 thanks to @Razetime - i forgot to drop a paren lol

```
+/⍎¨∘⍕∘!

```

Explanation:

```
+/⍎¨∘⍕∘!
       !  ⍝ factorial of ⍵
     ⍕    ⍝ convert to string
  ⍎¨      ⍝ produce digit vector
+/        ⍝ sum all digits

```

Has some problems with factorial of 900, this code will work fine for `⍵>40`:

```
b←({⍵⊣⍵.⎕CY'dfns'}⎕NS⍬).big
↑(+b/(⍎¨∘⍕∘(↑(×b/⍳))))

```

Try it online!

# Answer
> 3 votes
# Ruby, ~~63 60 53~~ 51 bytes

```
->n{a=0;f=(1..n).reduce:*;f.times{a+=f%10;f/=10};a}

```

Thanks to Martin for golfing help.

# Answer
> 3 votes
# Java 7, 148 bytes

```
int s=1,ret=0;while(i>1){s=s*i; i--;}String y=String.valueOf(s);for(int j=0;j<y.length();j++){ret+=Integer.parseInt(y.substring(j,j+1));}return ret;

```

# Answer
> 3 votes
## bash (seq,bc,fold,jq), ~~34~~ 33 bytes

Surely not the most elegant but for the challenge

```
seq -s\* $1|bc|fold -1|jq -s add

```

# Answer
> 3 votes
# Brachylog, 5 bytes

```
$!@e+

```

Try it online!

### Explanation

Basically the described algorithm:

```
$!       Take the factorial of the Input
  @e     Take the elements of this factorial (i.e. its digits)
    +    Output is the sum of those elements

```

# Answer
> 3 votes
# Pushy, 4 bytes

```
fsS#

```

Give input on the command line: `$ pushy facsum.pshy 5`. Here's the breakdown:

```
f      % Factorial of input
 s     % Split into digits
  S    % Push sum of stack
   #   % Output

```

# Answer
> 3 votes
# Octave, 30 bytes

```
@(n)sum(num2str(prod(1:n))-48)

```

Calculates the factorial by taking the product of the list `[1 2 ... n]`. Converts it to a string and subtracts `48` from all elements (ASCII code for `0`). Finally it sums it up :)

# Answer
> 3 votes
## C, 58 bytes

This is not perfect. Only works ones because a have to be -1 in start. The idea is to use two recursive function in one function. It was not as easy as I first thought.

```
a=-1;k(i){a=a<0?i-1:a;return a?k(i*a--):i?i%10+k(i/10):0;}

```

Usage and understandable format:

```
a = -1;
k(i){
   a = a<0 ? i-1 : a;
   return a ? k(i*a--) : i? i%10+k(i/10) :0;
}

main() {
   printf("%d\n",k(10));
}

```

Edit: I found metode that let use this function multiple time but then length is 62 bytes.

```
a,b;k(i){a=b?a:i+(--b);return a?k(i*a--):i?i%10+k(i/10):++b;}

```

# Answer
> 3 votes
# Perl 6, 21 bytes

```
{[+] [*](2..$_).comb}

```

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  [+]           # reduce the following with ｢&infix:<+>｣

    [*](        # reduce with ｢&infix:<*>｣
      2 .. $_   # a Range that include the numbers from 2 to the input (inclusive)
    ).comb      # split the product into digits
}

```

# Answer
> 3 votes
# Cubix, ~~33~~ 32 bytes

```
u*.$s.!(.01I^<W%NW!;<,;;q+p@Opus

```

Net form:

```
      u * .
      $ s .
      ! ( .
0 1 I ^ < W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Try it online!

# Notes

* Works with inputs up to and including 170, higher inputs result in an infinite loop, because their factorial yields the `Infinity` number (technically speaking, its a non-writable, non-enumerable and non-configurable property of the window object).
* Accuracy is lost for inputs 19 and up, because numbers higher than 253 (= 9 007 199 254 740 992) cannot be accurately stored in JavaScript.

# Explanation

This program consists of two loops. The first calculates the factorial of the input, the other splits the result into its digits and adds those together. Then the sum is printed, and the program finishes.

## Start

First, we need to prepare the stack. For that part, we use the first three instructions. The IP starts on the fourth line, pointing east. The stack is empty.

```
      . . .
      . . .
      . . .
0 1 I . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

We will keep the sum at the very bottom of the stack, so we need to start with `0` being the sum by storing that on the bottom of the stack. Then we need to push a `1`, because the input will initially be multiplied by the number before it. If this were zero, the factorial would always yield zero as well. Lastly we read the input as an integer.

Now, the stack is `[0, 1, input]` and the IP is at the fourth line, the fourth column, pointing east.

### Factorial loop

This is a simple loop that multiplies the top two elements of the stack (the result of the previous loop and the input - n, and then decrements the input. It breaks when the input reaches 0. The `$` instruction causes the IP to skip the `u`-turn. The loop is the following part of the cube. The IP starts on the fourth line, fourth column.

```
      u * .
      $ s .
      ! ( .
. . . ^ < . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Because of the `^` character, the IP starts moving north immediately. Then the `u` turns the IP around and moves it one to the right. At the bottom, there's another arrow: `<` points the IP back into the `^`. The stack starts as `[previousresult, input-n]`, where `n` is the number of iterations. The following characters are executed in the loop:

```
*s(
*   # Multiply the top two items
    #   Stack: [previousresult, input-n, newresult]
 s  # Swap the top two items
    #   Stack: [previousresult, newresult, input-n]
  ( # Decrement the top item
    #   Stack: [previousresult, newresult, input-n-1]

```

Then the top of the stack (decreased input) is checked against `0` by the `!` instruction, and if it is `0`, the `u` character is skipped.

### Sum the digits

The IP wraps around the cube, ending up on the very last character on the fourth line, initially pointing west. The following loop consists of pretty much all remaining characters:

```
      . . .
      . . .
      . . .
. . . . . W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

The loop first deletes the top item from the stack (which is either `10` or `0`), and then checks what is left of the result of the factorial. If that has been decreased to `0`, the bottom of the stack (the sum) is printed and the program stops. Otherwise, the following instructions get executed (stack starts as `[oldsum, ..., factorial]`):

```
N%p+q;;,s;
N          # Push 10
           #   Stack: [oldsum, ..., factorial, 10]
 %         # Push factorial % 10
           #   Stack: [oldsum, ..., factorial, 10, factorial % 10]
  p        # Take the sum to the top
           #   Stack: [..., factorial, 10, factorial % 10, oldsum]
   +       # Add top items together
           #   Stack: [..., factorial, 10, factorial % 10, oldsum, newsum]
    q      # Send that to the bottom
           #   Stack: [newsum, ..., factorial, 10, factorial % 10, oldsum]
     ;;    # Delete top two items
           #   Stack: [newsum, ..., factorial, 10]
       ,   # Integer divide top two items
           #   Stack: [newsum, ..., factorial, 10, factorial/10]
        s; # Delete the second item
           #   Stack: [newsum, ..., factorial, factorial/10]

```

And the loop starts again, until `factorial/10` equals 0.

# Answer
> 3 votes
## C, 47 bytes

```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}

```

usage:

```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
main() {
  printf("answer: %d\n",f(10,1));
}

```

# Answer
> 3 votes
# Brachylog (v2), 3 bytes

```
ḟẹ+

```

Try it online!

Same "algorithm" as the v1 answer by @Fatalize, just with better encoding.

# Answer
> 2 votes
# Python, 57 bytes

```
import math
lambda n:sum(map(int,str(math.factorial(n))))

```

**Try it online**

# Answer
> 2 votes
# Befunge 93, ~~56~~ 54 bytes

Saved 2 bytes do to using get instead of quotes. This let me shift the top 2 lines over 1, reducing unnecessary white space.

Try it online!

```
&#:<_v#:-1
: \*$<:_^#
g::v>91+%+00
_v#<^p00</+19
@>$$.

```

Explanation:

```
&#:<                Gets an integer input (n), and reverses flow direction
&#:< _v#:-1         Pushes n through 0 onto the stack (descending order)

:  \*$<:_^#         Throws the 0 away and multiplies all the remaining numbers together

(reorganized to better show program flow):
vp00< /+19 _v#<    Stores the factorial at cell (0, 0). Pushes 3 of whatever's in
> 91+%+ 00g ::^    cell (0, 0). Pops a, and stores a / 10 at (0, 0),
                   and adds a % 10 to the sum.

@>$$.              Simply discards 2 unneeded 0s and prints the sum.

```

# Answer
> 2 votes
# Javascript ES6 - 61 54 Bytes

```
n=>eval(`for(j of''+(a=_=>!_||_*a(~-_))(n,t=0))t-=-j`)

```

**EDIT:** Thank you Hedi and ETHproductions for shaving off 7 bytes. I'll have to remember that t-=-j trick.

# Answer
> 2 votes
## Batch, 112 bytes

```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
:g
@set/at+=f%%10,f/=10
@if %f% gtr 0 goto g
@echo %t%

```

Conveniently `set/a` works on a variable's current value, so it works normally inside a loop. Only works up to 12 due to the limitations of Batch's integer type, so in theory I could save a byte by assuming `f<1e9`:

```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
@for /l %%i in (1,1,9)do @set/at+=f%%10,f/=10
@echo %t%

```

But that way lies madness... I might as well hard-code the list in that case (97 bytes):

```
@call:l %1 1 1 2 6 6 3 9 9 9 27 27 36 27
@exit/b
:l
@for /l %%i in (1,1,%1)do @shift
@echo %2

```

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

```
f=(n,m=1,t=0)=>n?f(n-1,n*m):m?f(n,m/10|0,t+m%10):t

```

Only works up to `n=22` due to floating-point accuracy limitations.

# Answer
> 2 votes
# J, ~~12~~ 11 bytes

*Saved 1 byte thanks to cole!*

```
1#.10#.inv!

```

This simply applies sum (`1#.`) to the digits (using inverse `inv` of base conversion `#.` with a base of `10`) of the factorial (`!`) of the argument.

## Test cases

Note: the last two test cases are bigints, as marked by a trailing `x`.

```
   f=:10#.inv!
   (,. f"0) 10 19 469x 985x
 10    27
 19    45
469  4140
985 10053

```

# Answer
> 2 votes
# AHK, 60 bytes

```
a=1
Loop,%1%
a*=A_Index
Loop,Parse,a
b+=A_LoopField
Send,%b%

```

AutoHotkey doesn't have a built-in factorial function and the loop functions have long names for their built-in variables. The first loop is the factorial and the second is adding the digits together.

# Answer
> 1 votes
# C, ~~63~~ 60 bytes

-3 byte for `do...while` loop.

```
i;f(n){i=n;while(--n)i*=n;do n+=i%10;while(i/=10);return n;}

```

Ungolfed and usage:

```
i;
f(n){
 i=n;
 while(--n)
  i*=n;
 do
  n+=i%10;
 while(i/=10);
 return n;
}

main() {
 printf("%d\n",f(10));
}

```

# Answer
> 1 votes
**Q/KDB+ 41 Bytes**

```
sum{:"I"$string x}over'string prd 1+til n

```

Breakdown:

```
string prd 1+til n

```

Get the product from 1 to n

```
{:"I"$string x}

```

Function that accepts a string x and returns it converted to an integer.

```
over'

```

Iterate over the argument to it's right to the function on the left, passing each item in individually.

```
sum

```

Sum up the numbers output by the function at the end.

# Answer
> 1 votes
# PHP, 44 bytes

```
<?=array_sum(str_split(gmp_fact($argv[1])));

```

Well it's not clever, but it works. That said it turned out better than I thought (I thought I'd need to use `gmp_strval()` too).

# Answer
> 1 votes
## Pyke, 3 bytes (old version)

```
SBs

```

Explanation:

```
SB  -  product(range(1, input+1))
  s - digit_sum(^)

```

# Answer
> 1 votes
# Groovy, 61 bytes

```
{"${(1..it).inject{i,r->i*r}}".collect{0.parseInt(it)}.sum()}

```

Groovy doesn't even have factorial built-ins.

`"${(1..it).inject{i,r->i*r}}"` \- Compute factorial as string.

`.collect{0.parseInt(it)}` \- Turn the string into an array of integers.

`.sum()` \- Sum 'em.

# Answer
> 1 votes
# C#, 119 116 Bytes

*Edit: Saved 3 Bytes thanks to @TheLethalCoder*

Golfed:

```
long F(int n){long f=1;int s=0;for(;n>1;)f*=n--;foreach(var c in f.ToString().ToList())s+=int.Parse(c+"");return s;}

```

Ungolfed:

```
public long F(int n)
{
  long f = 1;
  int s = 0;
  for (; n > 1;)
    f *= n--;
  foreach (var c in f.ToString().ToList())
    s += int.Parse(c + "");
  return s;
}

```

Tried both a `long` and an `Int64` and it won't take higher than `n=20`, ultimately went with `long` because it is shorter...

Testing:

```
  Console.WriteLine(new DigitalSumFactorial().F(10));
  //27
  Console.WriteLine(new DigitalSumFactorial().F(19));
  //45
  Console.WriteLine(new DigitalSumFactorial().F(20));
  //54

```

# Answer
> 1 votes
# Wonder, 22 bytes

```
@sum <>""prod rng1+1#0

```

This only works for inputs \<= 21.

Usage:

```
(@sum <>""prod rng1+1#0)10

```

# Explanation

Increment argument, tail-exclusive range from 1 to result, product, split over empty string, and sum.

# Answer
> 1 votes
# F#, 80 bytes (74bytes for 32bit integer)

```
let rec s=function|0L->0L|y->y%10L+s(y/10L)
let g x={1L..x}|>Seq.fold (*) 1L|>s

```

# F#, 98 bytes (96bytes for 32bit integer)

```
let f x=([1L..x]|>List.fold (*) 1L).ToString().ToCharArray()|>Array.fold (fun a c-> a+int(c)-48) 0

```

Test with

```
f 10L
g 10L

```

Thanks to ais523 for the anonymous match function and formatting help.

# Answer
> 1 votes
## Lithp, 73 bytes

```
#N::((sum (map (split (+ "" (prod (seq 1 N))) "") #C::((- (asc C) 48)))))

```

I'm not sure if I should be counting `import` calls. Here is how you would use the above snippet:

```
(
    (import "lists")
    (def f #N::((sum (map (split (+ "" (prod (seq 1 N))) "") #C::((- (asc C) 48))))))
    (print (f 10))
)

```

It works by calculating the factorial using `prod/1`, converts it to a string by doing `(+ "" value)`, splits and maps the string to get the numeric value of each number (ASCII code - 48.) Lastly, we `sum/1` the resulting list.

# Answer
> 1 votes
# Pyt, ~~3~~ 2 bytes

Explanation:

```
        Implicit input
!       Get factorial
 Ś      Sum the digits

```

Try it online!

# Answer
> 1 votes
# Japt, 3 bytes

```
Êìx

```

Try it

Get the factorial, split to a digit array and reduce by addition.

# Answer
> 1 votes
# Tcl, 78 bytes

```
proc S n {proc F n {expr $n?($n)*\[F $n-1]:1}
expr [join [split [F $n] ""] +]}

```

Try it online!

# Answer
> 1 votes
# K (ngn/k), 10 bytes

**Solution:**

```
+/10\*/1+!

```

Try it online!

Explanation to follow.

# Answer
> 1 votes
# Java 10, 70 bytes

A lambda from `long` to `int`. Breaks for input over 20.

```
n->{var f=n;while(n>1)f*=--n;return(f+"").chars().map(c->c-48).sum();}

```

Try It Online

# Java 10, 163 bytes

Fully arbitrary precision. A lambda from `BigInteger` to `BigInteger`.

```
n->{var i=n;var f=n;while(n.compareTo(n.ONE)>0)f=f.multiply(n=n.subtract(n.ONE));return(f+"").chars().mapToObj(c->i.valueOf(c-48)).reduce(n.ZERO,(a,b)->a.add(b));}

```

Try It Online

## Ungolfed

```
n -> {
    var i = n;
    var f = n;
    while (n.compareTo(n.ONE) > 0)
        f = f.multiply(n = n.subtract(n.ONE));
    return (f + "").chars()
        .mapToObj(c -> i.valueOf(c - 48))
        .reduce(n.ZERO, (a, b) -> a.add(b))
    ;
}

```

# Answer
> 1 votes
# Perl 5 `-MList::Util=sum -MMath::BigInt -p`, 43 bytes

Supports arbitrarily large factorials.

```
$_=sum(Math::BigInt->new($_)->bfac()=~/./g)

```

Try it online!

# Perl 5 `-MList::Util=sum,product -p`, 27 bytes

Cannot handle extremely large factorials due to overflow.

```
$_=product 1..$_;$_=sum/./g

```

Try it online!

# Answer
> 1 votes
# Scala, 30 bytes

```
1.to(_).product+""map(_-48)sum

```

Try it online!

And a 34 byte solution without postfix syntax:

```
x=>(""+1.to(x).product:\0)(_+_-48)

```

Try it in Scastie

# Answer
> 1 votes
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
Sra

```

Try it online!

```
Sra
  a  # (num) range [1, a]
 r   # (lst) product
S    # (num) digit sum

```

# Answer
> 0 votes
# Java8 - 112 Chars

(First time here...)

```
String.valueOf(LongStream.rangeClosed(2,i).reduce(1,(a,b)->a*b)).chars().map(Character::getNumericValue).sum();

```

# Answer
> 0 votes
# Clojure, 65 bytes

```
(fn[i](apply +(map #(-(int %)48)(str(apply *(range 1(inc i)))))))

```

Straightforward, character `\0` has integer value of 48.

Easier to follow steps:

```
(defn f [i] (->> i inc (range 1) (apply *) str (map #(- (int %) (int \0)) (apply +)))

```

# Answer
> 0 votes
# Julia 0.6, 25 bytes

Julia functions are generic across input types, and generate optimized code for each combination of input types. This function works with machine sized integers or arbitrary precision integers depending on the type of the argument. eg

```
f(10) = 27
f(50) = -97 # overflowed
f(big(50)) = 216 # no overflow, but slower due to use of BigInt

```

```
x->sum(digits(prod(1:x)))

```

Try it online!

# Answer
> 0 votes
# Pari/GP, 16 bytes

```
n->sumdigits(n!)

```

Try it online!

# Answer
> 0 votes
# Python 3, 66 bytes

```
import math;print(sum(map(int,str(math.factorial(int(input()))))))

```

It gets factorial of number, splits it into an array, then prints it!

# Answer
> 0 votes
# MATL, 9 bytes

```
:p[]&V!Us

```

Try it online!

MATL port of Stewie Griffin's Octave answer. Works up to n=22, same as the Octave and R answers.

`:p` \- factorial.
`[]&V` \- string representation of the number, fully expanded (without the `[]&`, larger numbers use the scientific notation which won't do for our purposes).
`!U` transpose and convert back to numbers, getting individual digits.
`s` \- sum those digits.

The `[]&` part can be removed for -3 bytes, but then the range is further limited to only work up to 17, instead of 22.

I could stretch the input range to 23 with a couple of tricks, but that costs an additional 20 bytes:

`:1w5X2Y%"@*t10\~?10/]][]&V!Us`

(basically, use the `uint64` data type instead of the usual `double`, multiply by each number upto the given number, but divide away 10 whenever our product is divisible by it (since trailing zeros add nothing to the digit sum).)

That seems to be as far as we can go with MATLAB/MATL without doing an ad-hoc implementation of bignum in the program.

# Answer
> 0 votes
# Vyxal, 2 bytes

```
‼∑

```

Try it Online!

A very literal interpretation of the challenge: `sum_of_digits_of(factorial(input))`

# Answer
> 0 votes
# J-uby, 21 bytes

```
:+|:/&:*|:digits|:sum

```

Attempt This Online!

## Explanation

```
:+ | :/ & :* | :digits | :sum

:+ |                           # Range 1..n, then
     :/ & :* |                 # Reduce with product, then
               :digits | :sum  # Sum digits

```

# Answer
> 0 votes
# , 19 bytes

```
sum 10 vs prd 1+til

```

# k, 11 bytes

```
+/10\:*/1+!

```

`prd 1+til` generate the factorial of input

`10 vs` convert factorial to digits

# Answer
> 0 votes
# TI-Basic, 24 bytes (non-competing)

```
sum(10fPart(.1seq(int(Ans!/₁₀^(I)),I,0,int(log(Ans!

```

Only works for nonnegative integers up to 18, inclusive, and works up to 20 if you round to the nearest multiple of 9 when the input is greater than 5.

# Answer
> 0 votes
# Thunno 2 `S`, 1 byte

```
w

```

Attempt This Online!

## Thunno 2, 2 bytes

```
wS

```

Attempt This Online!

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


title: The 465 Arrangement

text:
# Question
Title: The 465 Arrangement
Here's the challenge. Write some code to output all the integers in a range. Sounds easy, but here's the tricky part. It will start with the lowest number, then the highest. Then the lowest number which isn't yet in the array. Then the highest which isn't yet in it.

## Example:

Lets take 1 to 5 as our start

The numbers are \[1, 2, 3, 4, 5\].

We take the first, so \[1\]. Remaining numbers are \[2, 3, 4, 5\]. We take the last, new array is \[1, 5\]. Remaining numbers are \[2, 3, 4\]. We take the first, new array is \[1, 5, 2\]. Remaining numbers are \[3, 4\]. We take the last, new array is \[1, 5, 2, 4\]. Remaining numbers are \[3\]. We take the first, new array is \[1, 5, 2, 4, 3\]. No numbers remaining, we're done. Output \[1, 5, 2, 4, 3\]

## Rules:

* This is code golf, write it in the fewest bytes, any language.
* No standard loopholes.
* Links to an online interpreter, please? (E.g. https://tio.run/)
* Two inputs, both integers. Low end of range, and high end of range.
* I don't mind what the data type of the output is, but it must show the numbers in the correct order.

## Examples

Low: 4 High: 6 Result: 4 6 5

---

Low: 1 High: 5 Result: 1 5 2 4 3

---

Low: -1 High: 1 Result: -1 1 0

---

Low: -1 high: 2 Result: -1 2 0 1

---

Low: -50 High: 50 Result: -50 50 -49 49 -48 48 -47 47 -46 46 -45 45 -44 44 -43 43 -42 42 -41 41 -40 40 -39 39 -38 38 -37 37 -36 36 -35 35 -34 34 -33 33 -32 32 -31 31 -30 30 -29 29 -28 28 -27 27 -26 26 -25 25 -24 24 -23 23 -22 22 -21 21 -20 20 -19 19 -18 18 -17 17 -16 16 -15 15 -14 14 -13 13 -12 12 -11 11 -10 10 -9 9 -8 8 -7 7 -6 6 -5 5 -4 4 -3 3 -2 2 -1 1 0

---

Happy golfing!

# Answer
> 15 votes
# , ~~38~~ ~~37~~ 36 bytes

```
function(a,b)rbind(a:b,b:a)[a:b-a+1]

```

Try it online!

* -1 byte thanks to @user2390246
* -1 byte thanks to @Kirill L.

Exploiting the fact that R stores matrices column-wise

# Answer
> 11 votes
# Haskell, 30 bytes

```
a%b=a:take(b-a)(b:(a+1)%(b-1))

```

Try it online!

# Answer
> 8 votes
# , ~~65~~ ~~64~~ ~~61~~ 60 bytes

-1 byte thanks to Robert S.

-4 more thanks to digEmAll

```
x=scan();z=x:x[2];while(sum(z|1)){cat(z[1],"");z=rev(z[-1])}

```

Try it online!

# Answer
> 7 votes
# Haskell, 39 bytes

```
a#b|a>b=a:b#(a-1)|a<b=a:b#(a+1)|1>0=[a]

```

Try it online!

# Answer
> 6 votes
# Python 2, 44 bytes

```
f=lambda a,b:[a]*(a==b)or[a]+f(b,a-cmp(a,b))

```

Try it online!

# Answer
> 5 votes
# PowerShell, ~~59~~ 48 bytes

```
param($a,$b)(($z=0..($b-$a))|%{$a+$_;$b-$_})[$z]

```

Try it online!

~~*(Seems long...)*~~

Takes input `$a` and `$b`, constructs the range `0 .. ($b-$a)`, stores that into `$z`, then loops through that range. The looping through that range is just used as a counter to ensure we get enough iterations. Each iteration, we put `$a` and `$b` on the pipeline with addition/subtraction. That gives us something like `1,5,2,4,3,3,4,2,5,1` so we need to slice into that from `0` up to the `$b-$a` (i.e., the count) of the original array so we're only left with the appropriate elements. That's left on the pipeline and output is implicit.

*-11 bytes thanks to mazzy.*

# Answer
> 5 votes
# 05AB1E, 6 bytes

```
ŸDvć,R

```

Try it online!

**Explanation**

```
Ÿ        # push range [min ... max]
 D       # duplicate
  v      # for each element in the copy
   ć,    # extract and print the head of the original list
     R   # and then reverse it

```

# Answer
> 4 votes
# Japt, 14 bytes

```
òV
íUs w)c vUl

```

Try it online!

# Answer
> 4 votes
# C# (Visual C# Interactive Compiler), 46 bytes

```
a=>b=>{for(;a<=b;Write(a+(b>a++?b--+"":"")));}

```

Saved 4 bytes thanks to dana!

Try it online!

# C# (Visual C# Interactive Compiler), 65 bytes

```
void z(int a,int b){if(a<=b){Write(a+(b>a?b+"":""));z(a+1,b-1);}}

```

Try it online!

# Answer
> 4 votes
# Stax, 7 bytes

```
É╓ÅìΔà▲

```

Run and debug it

# Answer
> 4 votes
# , 51 bytes

```
function(x,y,z=x:y)matrix(c(z,rev(z)),2,,T)[seq(z)]

```

Try it online!

Explanation: For a sequence `x:y` of length `N`, create a two-by-N matrix consisting of the sequence x:y in the top row and y:x in the bottom row `matrix(c(z,rev(z)),2,,T)`. If we select the first `N` elements of the matrix `[seq(z)]`, they will be chosen by column, giving the required output.

Outgolfed by digEmAll

# Answer
> 4 votes
# cQuents, 19 bytes

```
#|B-A+1&A+k-1,B-k+1

```

Try it online!

Note that it does not work on TIO right now because TIO's interpreter is not up to date.

## Explanation

```
#|B-A+1&A+k-1,B-k+1
                      A is the first input, B is the second input
#|B-A+1               n = B - A + 1
       &              Print the first n terms of the sequence
                      k starts at 1 and increments whenever we return to the first term
        A+k-1,         Terms alternate between A + k - 1 and
              B-k+1     B - k + 1
                       increment k

```

# Answer
> 4 votes
## Haskell, 39 bytes

```
f(a:b)=a:f(reverse b)
f x=x
a#b=f[a..b]

```

Try it online!

# Answer
> 4 votes
# Haskell, 30 bytes

```
l%h=l:take(h-l)(h:(l+1)%(h-1))

```

Usage: `3%7` gives \`\[3,7,4,6,5\]

For the inputs `l, h` the function calls recursively with the inputs `l+1, h-1`, and adds `l,h` to the beggining. Instead of any halting condition, the code uses `take(h-l)` to shorten the sequence to the right length (which would otherwise be an infinite sequence of increasing and decreasing numbers).

# Answer
> 4 votes
# Wolfram Language (Mathematica), ~~56~~ 54 bytes

This is my first time golfing!

```
f[a_,b_]:=(c=a~Range~b;Drop[c~Riffle~Reverse@c,a-b-1])

```

Try it online!

Saved 2 bytes using infix notation.

Explanation:

```
f[a_,b_]:=                                   \function of two variables
c=a~Range~b;                                 \list of integers from a to b
                           Reverse@c         \same list in reverse
                  c~Riffle~Reverse@c         \interleave the two lists
             Drop[c~Riffle~Reverse@c,a-b-1]  \drop last |a-b-1| elements (note a-b-1 < 0)

```

Alternatively, we could use `Take[...,b-a+1]` for the same result.

Tests:

```
f[4, 6]
f[1, 5]
f[-1, 1]
f[-1, 2]

```

Ouput:

```
{4, 6, 5}
{1, 5, 2, 4, 3}
{-1, 1, 0}
{-1, 2, 0, 1}

```

# Answer
> 4 votes
# JVM bytecode (OpenJDK asmtools JASM), 449 bytes

```
enum b{const #1=Method java/io/PrintStream.print:(I)V;static Method a:(II)V stack 2 locals 4{getstatic java/lang/System.out:"Ljava/io/PrintStream;";astore 3;ldc 0;istore 2;l:iload 2;ldc 1;if_icmpeq t;aload 3;iload 0;invokevirtual #1;iinc 0,1;iinc 2,1;goto c;t:aload 3;iload 1;invokevirtual #1;iinc 1,-1;iinc 2,-1;c:aload 3;ldc 32;i2c;invokevirtual java/io/PrintStream.print:(C)V;iload 0;iload 1;if_icmpne l;aload 3;iload 0;invokevirtual #1;return;}}

```

Ungolfed (and slightly cleaner)

```
 enum b {
    public static Method "a":(II)V stack 5 locals 4 {
        getstatic "java/lang/System"."out":"Ljava/io/PrintStream;";
        astore 3;
        ldc 0;
        istore 2;
    loop:
        iload 2;
        ldc 1;
        if_icmpeq true;
    false:
        aload 3;
        iload 0;
        invokevirtual "java/io/PrintStream"."print":"(I)V";
        iinc 0,1;
        iinc 2,1;
        goto cond;
    true:
        aload 3;
        iload 1;
        invokevirtual "java/io/PrintStream"."print":"(I)V";
        iinc 1,-1;
        iinc 2,-1;
        goto cond;
    cond:
        iload 0;
        iload 1;
        if_icmpne loop;
        aload 3;
        iload 0;
        invokevirtual "java/io/PrintStream"."print":"(I)V";
        return;
    }
}

```

Standalone function, needs to be called from Java as `b.a(num1,num2)`.

## Explanation

This code uses the method parameters as variables, as well as a boolean in local #3 deciding which number to output. Each loop iteration either the left or right is output, and that number is incremented for the left or decremented for the right. Loop continues until both numbers are equal, then that number is output.

...I have a distinct feeling I'm *massively* outgunned on the byte count

# Answer
> 4 votes
# MathGolf, 6 bytes

```
↨_x^─▀

```

Try it online!

## Explanation with `(1, 5)`

```
↨        inclusive range from a to b    [1, 2, 3, 4, 5]
 _       duplicate TOS                  [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]
  x      reverse int/array/string       [1, 2, 3, 4, 5], [5, 4, 3, 2, 1]
   ^     zip top two elements on stack  [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1]]
    ─    flatten array                  [1, 5, 2, 4, 3, 3, 4, 2, 5, 1]
     ▀   unique elements of string/list [1, 5, 2, 4, 3]

```

The reason why this works is due to the fact that all elements in the output should be unique, so the unique elements operator will filter out the second half of the array, producing the correct output.

# Answer
> 3 votes
# APL (dzaima/APL), 21 bytes

```
⌈⊢+.5×-+∘(⌽×¯1*)∘⍳1+-

```

Try it online!

# Answer
> 3 votes
# Japt, 7 bytes

Takes input as an array.

```
rõ
ÊÆÔv

```

Try it or run all test cases

```
         :Implicit input of array U=[low,high]
r        :Reduce by
 õ       :  Inclusive, reversed range (giving the range [high,low])
\n       :Reassign to U
Ê        :Length
 Æ       :Map the range [0,Ê)
  Ô      :  Reverse U
   v     :  Remove the first element

```

# Answer
> 3 votes
# MATL, 8 bytes

```
&:t"1&)P

```

Try it online!

### Explanation

```
&:      % Take two inputs (implicit). Two-input range
t       % Duplicate
"       % For each
  1&)   %   Push first element, then an array with the rest
  P     %   Reverse array
        % End (implicit). Display (implicit)

```

# Answer
> 3 votes
# Forth (gforth), 52 bytes

```
: f 2dup - 1+ 0 do dup . i 2 mod 2* 1- - swap loop ;

```

Try it online!

### Explanation

Loop from 0 to (End - Start). Place End and Start on top of the stack.

Each Iteration:

* Output the current number
* Add (or subtract) 1 from the current number
* Switch the current number with the other number

### Code Explanation

```
: f           \ start new word definition
  2dup -      \ get the size of the range (total number of integers)
  1+ 0        \ add 1 to the size because forth loops are [Inclusive, Exclusive)
  do          \ start counted loop from 0 to size+1
    dup .     \ output the current top of the stack
    i 2 mod   \ get the index of the loop modulus 2
    2* 1-     \ convert from 0,1 to -1,1
    -         \ subtract result from top of stack (adds 1 to lower bound and subtracts 1 from upper)
    swap      \ swap the top two stack numbers
  loop        \ end the counted loop
;             \ end the word definition

```

# Answer
> 3 votes
# JavaScript, 40 bytes

```
l=>g=h=>h>l?[l++,h--,...g(h)]:h<l?[]:[l]

```

Try It Online!

# Answer
> 3 votes
# Julia 0.7, 29 bytes

```
f(a,b)=[a:b b:-1:a]'[1:1+b-a]

```

Try it online!

# Answer
> 3 votes
# Brachylog, 15 bytes

```
⟦₂{∅|b↔↰T&hg,T}

```

Input is a 2-element list \[lo, hi\]. Note that underscore is used for negative numbers. Try it online!

### Explanation

```
⟦₂               2-argument inclusive range: [1,5] -> [1,2,3,4,5]
  {           }  Call this recursive predicate to calculate the output:
   ∅               Base case: the input is empty list; nothing to do
    |              Otherwise (recursive case):      [1,2,3,4,5]
     b             Behead the input list            [2,3,4,5]
      ↔            Reverse                          [5,4,3,2]
       ↰           Call the predicate recursively   [5,2,4,3]
        T          Label the result T
         &         Also, with the input list,
          h        Take the head                    1
           g       Wrap it in a list                [1]
            ,T     Append T from earlier            [1,5,2,4,3]

```

# Answer
> 3 votes
# 05AB1E, 5 bytes

```
ŸÂ.ιÙ

```

Takes input as upper first.

Explanation:

```
ŸÂ.ιÙ   //full program
Ÿ       //push [min .. max]                stack: [[4, 5, 6]]
 Â      //push range and reversed range    stack: [[4, 5, 6], [6, 5, 4]]
  .ι    //interleave                       stack: [[4, 6, 5, 5, 6, 4]]
    Ù   //deduplicate                      stack: [[4, 6, 5]]

```

Try it online!

# Answer
> 2 votes
# Java (JDK), 52 bytes

```
(l,h,o)->{for(int i=0;l<=h;i^=1)o.add(i<1?l++:h--);}

```

Try it online!

# Answer
> 2 votes
# Ink, 45 bytes

```
=h(I,A)
{I<=A:{I} {I<A:{A} ->h(I+1,A-1)}}->->

```

~~(I don't think there's an online interpreter for Ink, sorry)~~
Try it online!

Defines a stitch called h, which takes two arguments I and A, which are the bounds of the range.

Outputs by printing values, separated by spaces, to stdout.

# Explanation

```
=h(min, max) // Define the stitch.
{min <= max:{min}/* print min unless it's greater than max */{min < max: {max} /*Also print max if it's greater than min*/->h(min+1, max-1)/*Then divert, with the arguments changed*/}}
->-> // If we didn't divert earlier, divert to wherever the stitch was called from

```

# Answer
> 2 votes
# Perl 5 `-ln`, 37 bytes

```
@.=$_..<>;say shift@.,$/,pop@.while@.

```

Try it online!

# Answer
> 2 votes
# Jelly, 6 bytes

```
rạṂ¥Þ,

```

Try it online!

# Answer
> 2 votes
# Pyth, ~~10~~ 8 bytes

```
{.iF_B}F

```

Try it here

### Explanation

```
{.iF_B}F
      }FQ  Generate the range between the (implicit) inputs.
 .iF_B     Interleave it with its reverse.
{          Deduplicate.

```

# Answer
> 2 votes
# APL+WIN, bytes ~~17, 13~~, 26

4 bytes saved thank to Adám plus 13 bytes see Jonah's comment

```
(⍴m)↑∊m,¨⌽m←(1↓m)+0,⍳-/m←⎕

```

Try it online! Courtesy of Dyalog Classic

Explanation:

```
m←(1↓m)+0,⍳-/m←⎕ Prompts high end of range followed by low end and generates vector

∊m,¨⌽m Reverse the vector, pair elements from both vectors and flatten.

(⍴m)↑ Select the elements to the length of the original vector

```

# Answer
> 2 votes
# Clean, 48 bytes

```
import StdEnv
$a b|a<>b=[a: $b(a+sign(b-a))]=[a]

```

Try it online!

# Answer
> 2 votes
# JavaScript, 35 bytes

```
f=(a,b,s=1)=>a-b?a+[,f(b,a+s,-s)]:a

```

Try it online!

Thanks to Arnauld, 1 byte saved.

# Answer
> 2 votes
# Ruby, ~~37~~ ~~36~~ 33 bytes

```
f=->a,b{a>b ?[]:[a,b]|f[a+1,b-1]}

```

Try it online!

Recursive version with 3 bytes saved by G B.

### Ruby, 38 bytes

```
->a,b{d=*c=a..b;c.map{d.reverse!.pop}}

```

Try it online!

Non-recursive version.

# Answer
> 2 votes
# Cubix, 16 bytes

```
;w(.II>sO-?@;)^/

```

Try it here

### Cubified

```
    ; w
    ( .
I I > s O - ? @
; ) ^ / . . . .
    . .
    . .

```

### Explanation

Basically, this moves the two bounds closer together one step at a time until they meet. Each time through the loop, we `s`wap the bounds, `O`utput, take the difference, and increment with `)` or decrement with `(` based on the sign.

# Answer
> 2 votes
# tinylisp, 48 bytes

```
(d f(q((A B)(c A(i(e A B)()(f B((i(l A B)a s)A 1

```

Try it online!

### Explanation

The code defines a recursive function `f` that takes two arguments `A` and `B`, which are initially the lower and upper bounds of the range.

* Base case: if `A = B`, return a list containing the single element `A`
* Recursive case: prepend `A` to the result of a recursive call:
    + If `A < B`, recurse with arguments `B` and `A+1`
    + If `A > B`, recurse with arguments `B` and `A-1`

For example, with initial arguments 1 and 5:

```
Value   Next call
1       5, 2
5       2, 4
2       4, 3
4       3, 3
3       Return

```

with a resulting list of `(1 5 2 4 3)`.

Somewhat ungolfed:

```
(load lib/utilities)

(def f
  (lambda (A B)
    (cons A
      (if (equal? A B)
        nil
        (f B
          ((if (less? A B) add2 sub2)
            A
            1))))))

```

# Answer
> 2 votes
# C (gcc), 46 bytes

A recursive function, call as `f(low, high)`. As an extra 0-byte bonus, if you call `f(high, low)` the opposite arrangement is produced.

```
f(x,y){printf("%i ",x);x-y&&f(y,x+1-2*(x>y));}

```

Try it online!

## Degolf

```
f(x,y)
{
  printf("%i ",x); // Print the value of x
  x-y&& // If x-y == 0, the && operator shorts and the
        // recursion ends.
    f(y,x+1-2*(x>y)); // Adjust x by 1 towards y, and
                      // recurse with x and y swapped.
}

```

# Answer
> 1 votes
# C# (.NET Core), 66 bytes

```
a=>b=>{var s="";for(;b>=a;)s+=a+" "+(b==a++?"":b--+" ");return s;}

```

Try it online!

# Answer
> 1 votes
# Haskell, 52 bytes

```
x?y=take(y+1-x).map head$iterate(reverse.tail)[x..y]

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~54~~ ~~53~~ 52 bytes

* Saved ~~a byte~~ two bytes thanks to Rogem.

```
s=1;f(x,y){printf("%d ",s*x),s=x-y?f(-y,~x,s=-s):1;}

```

Try it online!

# Answer
> 1 votes
# C#(Visual C# Interactive Compiler), 62 bytes

```
void a(int i,int j){Write((j-i)%2==0?i++:j--);if(i<=j)a(i,j);}

```

Try it online!

# Answer
> 1 votes
# Gol\>\<\>, 22 bytes

```
IIT}:nP}:nM2K(?t2K=?h;

```

Fixed!!! It had a major bug where it would sometimes append a zero when not necessary, but no longer!

Try it online!

# Answer
> 1 votes
# Charcoal, 17 bytes

```
≔…·ＮＮθＷθ«≔⮌θθ⟦Ｉ⊟θ

```

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

```
≔…·ＮＮθ

```

Create an inclusive range between the two inputs.

```
Ｗθ«

```

Repeat until it is empty.

```
≔⮌θθ

```

Reverse it.

```
⟦Ｉ⊟θ

```

Remove the last element and print it on its own line.

# Answer
> 1 votes
# Perl 6, 32 bytes

```
{flat($_ Z [R,] $_)[^*/2]}o&[..]

```

Try it online!

Not too complicated, but there's a couple of tricks that help make the program shorter

### Explanation:

```
{                        }o&[..]   # Convert the two inputs to a range
      $_ Z [R,] $_                 # Zip the range with its reverse
 flat(            )                # Flatten
                   [^*/2]          # And take the first half of the elements

```

# Answer
> 1 votes
# PHP, ~~93~~ ~~92~~ 81 bytes

Standalone program, **81 bytes**:

```
for($a=range($argv[1],$argv[2]);$a;)echo$x++%2?array_pop($a):array_shift($a),' ';

```

Try it online!

As a function, **92 bytes**:

```
function($l,$h){for($a=range($l,$h);$a;)$b[]=$x++%2?array_pop($a):array_shift($a);return$b;}

```

Try it online!

```
function ( $l, $h ) {
    for( $a = range( $l, $h ); $a; ) {
        $b[] = $x++ % 2 ? array_pop( $a ) : array_shift( $a );
    }
    return $b;
}

```

Well, I thought it was a worth-trying idea. Perhaps in a more succinct language, this would work better. The Golf is not strong with this one.

# Answer
> 1 votes
# JavaScript (Node.js), ~~39~~ 37 bytes

```
f=a=>b=>a+[,a-b?f(b)(a<b?a+1:a-1):[]]

```

Try it online!

# Answer
> 1 votes
# F# (.NET Core), ~~69~~ 67 bytes

Translation of @nimi's answer.

```
fun a b->let rec h=function|a::b->[a]@h(List.rev b)|n->n in h[a..b]

```

Try it online!

# Answer
> 1 votes
# Shortcuts for iOS, 20 Actions, 4 KB

Shortcuts is a visual scripting language, so the code is linked as a screenshot and download.

Screenshot (very tall) / Shortcut iCloud link

How it works:

```
getVariable (input.s)
if Equals (input.s)

```

This tests if input.s exists. input.s will be nothing if it does not exist. In shortcuts, nothing does not equal itself.

```
otherwise

```

There is no way to test for not equal in shortcuts other than using the else side of an if statement

```
dictionary {a:input.a, b:input.b, c:1}
setVariable (input)

```

To set a single key in a dictionary, you need to get the variable, set dictionary value, and re-set the variable. Creating a new dictionary here saves one action but takes more bytes. I am optimizing for actions here.

```
getVariable (input.a)
if Equals (input.b)
  getVariable(input.a)
otherwise

```

If both a and b are the same, this range only has one value. Values passed to otherwise are returned by End, similar to how ternary operators work in many languages.

```
number 0
calculate - (input.s)
getVariable (input.a)
calculate + (input.s)

```

No set variable is required because instead, magic variables are used to get the values from the calculate actions

```
dictionary{a: input.b, b:(Calculation Result), c: (Calculation Result)}

```

The two calculation results refer to different actions. The first to the a+s, and the second to the 0-s.

```
runShortcut ch-arrangement

```

Run this shortcut again with the new input and return the result.

To run, pass a dictionary containing a and b to the shortcut. Output is the list as a string (comma seperated). Screenshot / Link

There is no online interpreter for this. You need an iOS device and the Shortcuts app.

Logic from @ovs's javascript answer

# Answer
> 1 votes
# Clojure, 62 bytes

```
#(distinct(let[r(range %1(inc %2))](interleave r(reverse r)))

```

Try it online!

Wow Clojure is a terrible golfing language. Still fun though.

# Answer
> 1 votes
# VBA (Excel), 62 bytes

Using immediate window and \[a1\] and \[a2\] as input.

```
a=[a1]:b=[a2]:For x=0To(b-a)/2:?a+x &IIf(b-x=a+x,"",b-x);:Next

```

# Answer
> 1 votes
# , 23 bytes

```
[:(#$],@,.|.)[+i.@>:@-~

```

Try it online!

# Answer
> 1 votes
**C (compiled with VC++ (Visual Studio 2017)) 264bytes**

```
#include "stdafx.h"
void f(int l,int u){for(int t=1,h=0,H=0,i=0;i<u-l+1;i++,t^=1)printf("%d ",t?l+h++:u-H++);}void main(){f(1,5);}

```

choosing other Compiler may eliminate the Need for the include but vs2017 won't let me ommit it w/o Errors. the idea is to just use variables to Keep track of how many numbers have to be added to the Minimum or have to be subtracted from the maximum (2seperate variables) another variable is used to Keep track of from where the value has to be taken from front or from end. Setting it to 1 means lowest bit is set xor-ing it with 1 makes it toggle. i run a loop with the amount of iterations it takes to solve the Problem. inside the printf i use the Array Bounds and my variables to generate the number needed and increment my helper variables all at once. using the ternary Operator exp?then:else saves a few Bytes as it replaces a if-else Statement. further saving come through use of multiple variables defined in the for loop instead of only one (typically i) and putting the xor in the loop Header removes the Need for curly braces.

every Thing else i did is ommit spaces and linebreaks where possible and only use 1 character variable names and omitting ()s where ever possible

# Answer
> 1 votes
**Java 8 (JDK)**: 113, 98, **124** bytes

```
(l,h)->{String s="";while(h>=l)s+=l+++" "+h--+" ";return s.substring(0,s.length()-(l-h==2?(l+(l<0?".":"")).length()+2:1));};

```

Thanka to Sriotchilism O'Zaic and Embodiment of Ignorance for saving me 15 bytes! Unfortunately those bytes were used to fix a bug Jo King mentioned.
Try it online

My first every golf code submission. Code is a functional interface that takes 2 integers and builds a string from those integers. The substring hack at the end hides a little quirk that duplicates the last element of the "array." Probably not the best solution, but for my first ever submission, I think I did well :)

# Answer
> 1 votes
# \>\<\>, 20 bytes

```
:{:&=?v:1+&}
  oanr/

```

Try it online!

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

```
	A =INPUT
	B =INPUT
L	OUTPUT =LE(A,B) A	:F(END)
	OUTPUT =GT(B,A) B
	A =A + 1
	B =B - 1	:(L)
END

```

Try it online!

# Answer
> 1 votes
# 1. Python 3.5, 123 bytes

Script takes two params: interval from, interval to.

```
from sys import*;v=[*range(int(argv[1]),int(argv[2])+1)];o=[]
for i in range(len(v)):v.reverse();o.append(v.pop())
print(o)

```

example:

```
$ ./script.py 1 5
[1, 5, 2, 4, 3]

$ ./script.py -5 6
[-5, 6, -4, 5, -3, 4, -2, 3, -1, 2, 0, 1]

```

## Explanation

```
# create range input params
v=[*range(int(argv[1]),int(argv[2])+1)]

# define ampty output array
o=[]

# loop input-array-lenght times
for i in range(len(v)):

    # reverse input array
    v.reverse()

    # append last input element to output
    o.append(v.pop())

# print output array
print(o)

```

# Answer
> 1 votes
# Vyxal, 6 bytes

```
‹rI÷ṘY

```

Try it Online!

### Explained

```
‹rI÷ṘY
‹      # decrement
 r     # range
  I÷   # split into two halves
    Ṙ  # reverse
     Y # interleave

```

# Answer
> 1 votes
# Thunno 2, 4 bytes

```
IḲIU

```

Attempt This Online!

Takes the upper number first.

#### Explanation

```
IḲIU  # Implicit input
I     # Inclusive range between the two inputs
 Ḳ    # Bifurcate: reverse a copy
  I   # Interleave them together
   U  # Uniquify the list
      # Implicit output

```

---
Tags: code-golf
---