title: Finding "sub-palindromes".

text:
# Question
Title: Finding "sub-palindromes".
The shortest code that finds all *unique* "sub-palindromes" of a string, that is: any substring with length \> 1 that is a palindrome.

eg.1

```
input: "12131331"
output: "33", "121", "131", "313", "1331"

```

eg.2

```
input: "3333"
output: "33", "333", "3333"

```

# Answer
## J, 24 ~~31~~ ~~40~~

```
~.(#~(1<#*]-:|.)&>),<\\.

```

Sample use:

```
   ~.(#~(1<#*]-:|.)&>),<\\. '12131331'
┌───┬───┬───┬────┬──┐
│121│131│313│1331│33│
└───┴───┴───┴────┴──┘
   ~.(#~(1<#*]-:|.)&>),<\\. '3333'
┌──┬───┬────┐
│33│333│3333│
└──┴───┴────┘

```

Take that, GolfScript!
> 11 votes

# Answer
## Python 124

```
r=raw_input()
l=range(len(r))
print', '.join(set('"'+r[i:j+1]+'"'for i in l for j in l if i<j and r[i:j+1]==r[i:j+1][::-1]))

```
> 7 votes

# Answer
## Haskell 98, 88 ~~91~~ ~~96~~

```
import List
main=interact$show.filter(\x->length x>1&&x==reverse x).nub.(tails=<<).inits

```
> 5 votes

# Answer
## Python - 138 136

This code does not duplicate sub-palindromes.

```
r=raw_input()
i,l=0,len(r)
j=l
a=[]
while i<l-1:
 t=r[i:j];j-=1
 if t==t[::-1]:a+=['"'+t+'"']
 if j<i+2:i+=1;j=l
print", ".join(set(a))

```
> 3 votes

# Answer
## Ruby - 126 102 97 characters

```
s=gets
*m=*0..s.size
puts m.product(m).map{|h,j|(c=s[h,j+1]).size>1&&c==c.reverse ? c:0}.uniq-[0]

```
> 3 votes

# Answer
## Golfscript, 48 characters

subpalindrome.gs

```
{,}{(;}/{{,}{);}/}%{+}*{.,1>\.-1%=*},.&{`}%", "*

```

Usage:

```
echo "12131331" | ruby golfscript.rb subpalindrome.gs

```

The first operation `{,}{(;}/` turns a string into a list of trailing-substrings. A similar leading-substrings transform is then mapped over the result. Then flatten with `{+}*`, filter for palindromes using the predicate `.,1>\.-1%=*`, grab unique values with `.&`, then pretty print.

It would be neater to extract the trailing-substrings transform as a block and reuse it as a replacement for leading-substrings after reversing each trailing substring, but I can't figure out a succinct way of doing that.
> 3 votes

# Answer
# Vyxal, 7 bytes

```
ǎU~Ḣ'Ḃ=

```

Try it Online!

-1 thanks to lyxal

```
 U      # Unique
ǎ       # Substrings
  ~     # Where
   Ḣ    # Length > 1
    '   # And
     Ḃ= # Is palindromic

```
> 3 votes

# Answer
## Haskell - 170, 153

```
import Data.List
import Data.Set
p a=fromList$[show x|x<-subsequences a,x==reverse x,length x>1]
main=getLine>>=(\x->putStrLn$intercalate", "$toList$p x)

```
> 2 votes

# Answer
### Windows PowerShell, 104 ~~109~~ ~~111~~

```
0..($l=($s="$input").length-1)|%{($a=$_)..$l|%{-join$s[$a..$_]}}|sort -u|?{$_[1]-and$_-eq-join$_[$l..0]}

```

This expects the input on stdin and will throw all found palindromes one per line on stdout:

```
PS Home:\SVN\Joey\Public\SO\CG183> '12131331'| .\subp.ps1
33
121
131
313
1331

```

(When run from `cmd` it becomes `echo 12131331|powershell -file subp.ps1` – it's just that `$input` takes a slightly different meaning depending on how the script was called, but it can be stdin, just not interactively.)

**2011-01-30 13:57** (111) – First attempt.

**2011-01-30 13:59** (109) – Inlined variable declaration.

**2011-06-02 13:18** (104) – Redone substring finding by joining a char array instead of calling `.Substring()` and inlined a bit more.
> 2 votes

# Answer
## J, 48

```
f=:,@:".
h=:\\.
~.(#~10&<)((]h-:"0&f|.h)#[:f]h)

```

eg

```
~.(#~10&<)((]h-:"0&f|.h)#[:f]h) '12131331'
121 131 313 1331 33

```
> 2 votes

# Answer
## Prolog, 92

```
f(S,P):-append([_,X,_],S),X=[_,_|_],reverse(X,X),atom_codes(P,X).
p(S,R):-setof(P,f(S,P),R).

```

Sample use:

```
?- p("12131331",R).
R = ['121', '131', '1331', '313', '33'].

?- p("3333",R).
R = ['33', '333', '3333'].

```
> 2 votes

# Answer
# Q, 78

```
{a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}

```

usage

```
q){a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}"12131331"
"121"
"131"
"313"
"1331"
"33"
q){a::x;(?)(,/)b@'(&:')({x~(|:)x}'')b:-1_1_'({(sublist[;a]')x,'1+c}')c::(!)(#)a}"3333"
"33"
"333"
"3333"

```
> 2 votes

# Answer
## Retina, ~~34~~ 27 bytes

```
&@!`(.)+.?(?<-1>\1)+(?(1)^)

```

Try it online!

The test suite needs an `M` because it is followed by another stage to insert empty lines between test cases.

### Explanation

```
&@!`(.)+.?(?<-1>\1)+(?(1)^)

```

Print (`!`) all unique (`@`), overlapping (`&`) matches of the regex `(.)+.?(?<-1>\1)+(?(1)^)`. This matches a palindrome of length 2 or more using balancing groups. There's a caveat to the "all overlapping matches" part: we can get at most one match per starting position. However, if two palindromes of different length begin at the same position, the shorter palindrome will appear again at the end of the longer palindrome. And since the greediness of `+` prioritises longer matches, we're getting all palindromes anyway.
> 2 votes

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

```
ŒÙʒÂQ}žQSK

```

Try it online!
> 2 votes

# Answer
# Japt, 9 bytes

```
ã â fÅfêU

```

Try it

```
ã â fÅfêU     :Implicit input of string
ã             :Substrings
  â           :Deduplicate
    f         :Filter elements that return truthy
     Å        :  Slice off first character
       f      :Filter elements that return true
        êU    :  Test for palindrome

```
> 2 votes

# Answer
# Factor, 70 bytes

```
[ all-subseqs [ length 1 > ] filter [ dup reverse = ] filter members ]

```

Try it online!

Having the two filters is actually shorter than having a single filter with some kind of `and` logic, or applying a single `filter` to two quotations with `bi@`.

* `all-subseqs` Get all subsequences of the input.
* `[ length 1 > ] filter` Take those with a length greater than one.
* `[ dup reverse = ] filter` Take the palindromes.
* `members` Remove duplicates.

Using locals ties the byte count:

```
[ all-subseqs [| s | s length 1 > s s reverse = and ] filter members ]

```
> 2 votes

# Answer
## Scala 156 170

```
object o extends App{val l=args(0).length-2;val r=for(i<-0 to l;j<-i to l;c=args(0).substring(i,j+2);if(c==c.reverse))yield c;print(r.toSet.mkString(" "))}

```

```
object o{def main(s:Array[String]){val l=s(0).length-2;val r=for(i<-0 to l;j<-i to l;c=s(0).substring(i,j+2);if(c==c.reverse)) yield c;println(r.distinct.mkString(" "))}}

```
> 1 votes

# Answer
## Python, 83 102 chars

```
s=lambda t:(t[1:]or())and(t,)*(t==t[::-1])+s(t[1:])+s(t[:-1])
print set(s(input()))

```

The phrase `(t[1:]or())and...` is equivalent to `(...)if t[1:]else()` and saves one character! I'm overly proud of this, given the savings.

Example:

```
python x
"51112232211161"
set(['11', '22', '11122322111', '161', '111', '112232211', '1223221', '22322', '232'])

```
> 1 votes

# Answer
## Perl, 112

```
$_=<>;chop;s/./$&$' /g;
map{/../&&$_ eq reverse&&$h{$_}++}split/ /
  for grep{s/./$`$& /g}split/ /;
print for keys %h

```
> 1 votes

# Answer
## Scala 127

```
object p extends App{val s=args(0);print(2.to(s.size).flatMap(s.sliding(_).toSeq.filter(c=>c==c.reverse)).toSet.mkString(" "))}

```

To keep this an apples to apples comparison with the other Scala answer, I also made mine an object that extends App. Rather than iterate the input string manually and use substring, I leveraged sliding() to create a sequence of all the substrings for me.
> 1 votes

# Answer
## Clojure, 81 bytes

```
#(set(for[i(range 2(+(count %)1))p(partition i 1 %):when(=(reverse p)(seq p))]p))

```

`for` was a perfect match here :) Could use `:when(=(reverse p)p)` if input was a list of characters OR a full string didn't count as a palindrome, actually in that case the max range of `i` could be `(count %)` as well.

Most compact case for reference:

```
#(set(for[i(range 2(count %))p(partition i 1 %):when(=(reverse p)p)]p))

```
> 1 votes

# Answer
# JavaScript (ES6), 120 bytes

```
a=>{for(b=0,c=d=a.length,e=[];b<d;--c<b+2?(b++,c=d):1)(f=a.slice(b,c))==f.split``.reverse().join``&&e.push(f);return e}

```

This function takes a string as input and outputs an array.
> 1 votes

# Answer
# Jelly, 9 bytes

```
ẆQŒḂÐfḊÐf

```

Try it online!
> 1 votes

# Answer
# Perl 6,  ~~35~~  32 bytes

```
{unique ~«m:ex/(.+).?<{$0.flip}>/}

```

Test it

```
{set ~«m:ex/(.+).?<{$0.flip}>/}

```

Test it

## Expanded:

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

  set             # turn into a Set object (ignores duplicates)

  ~«\             # stringify ｢~｣ all of these ｢«｣ (possibly in parrallel)
                  # otherwise it would be a sequence of Match objects

  m               # match
  :exhaustive     # in every way possible
  /
    ( .+ )        # at least one character ｢$0｣
    .?            # possibly another character (for odd sized sub-palindromes)
    <{ $0.flip }> # match the reverse of the first grouping
  /
}

```
> 1 votes

# Answer
# Perl, ~~43~~ 40 bytes

Includes `+1` for `n`

```
perl -nE 's/(?=((.)((?1)|.?)\2)(?!.*\1))/say$1/eg' <<< 12131331

```
> 1 votes

# Answer
# Coconut, 69 bytes

```
def f(s)=s and{s*(s[::-1]==s>""<s[1:])}-{""}|f(s[1:])|f(s[:-1])or s{}

```

Try it online!

---

# Python 2, 73 bytes

```
f=lambda s:s and{s*(s[::-1]==s>""<s[1:])}-{""}|f(s[1:])|f(s[:-1])or set()

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Classic), 27 bytes

```
{∪⍵/⍨≡∘⌽¨⍨⍵}∘⊃(,/1↓⍳∘≢,/¨⊂)

```

Try it online!

```
{∪⍵/⍨≡∘⌽¨⍨⍵}∘⊃(,/1↓⍳∘≢,/¨⊂)    Monadic train:
                           ⊂     Enclose the input, ⊂'12131331'
                     ⍳∘≢          Range from 1 to length of input
                     ⍳∘≢,/¨⊂      List of list of substrings of each length
                   1↓            Remove the first list (length-1 substrings)
               ⊃ ,/              Put the rest of the substrings into a single list.
{∪⍵/⍨≡∘⌽¨⍨⍵}                   To the result, apply this function which
                                   keeps all palindromes from a list:
      ≡∘⌽¨⍨⍵                    Boolean value of whether each (¨) string in argument
      ≡∘⌽ ⍨                     is equal to its own reverse

  ⍵/⍨                           Replicate (filter) argument by those values.
                                 This yields the length >1 palindromes.
∪                                Remove duplicates from the list of palindromes.

```
> 1 votes

# Answer
# APL(NARS), 65 chars, 130 bytes

```
{0=≢m←∪b/⍨{1≥≢⍵:0⋄∧/⍵=⌽⍵}¨b←↑∪/{x[⍵;]⊂y}¨⍳≢x←11 1‼k k⊢k←≢y←⍵:⍬⋄m}

```

test:

```
  r←{0=≢m←∪b/⍨{1≥≢⍵:0⋄∧/⍵=⌽⍵}¨b←↑∪/{x[⍵;]⊂y}¨⍳≢x←11 1‼k k⊢k←≢y←⍵:⍬⋄m}
  o←⎕fmt
  o r '1234442'
┌2───────────┐
│┌2──┐ ┌3───┐│
││ 44│ │ 444││
│└───┘ └────┘2
└∊───────────┘
  o r '3333'
┌3───────────────────┐
│┌4────┐ ┌3───┐ ┌2──┐│
││ 3333│ │ 333│ │ 33││
│└─────┘ └────┘ └───┘2
└∊───────────────────┘
  o r  "12131331"
┌5─────────────────────────────────┐
│┌4────┐ ┌3───┐ ┌2──┐ ┌3───┐ ┌3───┐│
││ 1331│ │ 121│ │ 33│ │ 313│ │ 131││
│└─────┘ └────┘ └───┘ └────┘ └────┘2
└∊─────────────────────────────────┘
  o r '1234'
┌0─┐
│ 0│
└~─┘

{0=≢m←∪b/⍨{1≥≢⍵:0⋄∧/⍵=⌽⍵}¨b←↑∪/{x[⍵;]⊂y}¨⍳≢x←11 1‼k k⊢k←≢y←⍵:⍬⋄m}
 y←⍵  assign the argument to y (because it has to be used inside other function)
 x←11 1‼k k⊢k←≢y   assign the lenght of y to k, call the function 11 1‼k k
                   that seems here find all partition of 1 2 ..k
 {x[⍵;]⊂y}¨⍳≢      make partition of arg ⍵ using that set x
 ∪/                set union with precedent to each element of partition y (i don't know if this is ok)
 b←↑               get first assign to b
 {1≥≢⍵:0⋄∧/⍵=⌽⍵}¨ for each element of b return 1 only if the argument ⍵ is such that
                   "∧/⍵=⌽⍵" ⍵ has all subset palindrome, else return 0
 b/⍨               get the elements in b for with {1≥≢⍵:0⋄∧/⍵=⌽⍵} return 1
 m←∪               make the set return without ripetition element, and assign to m
 0=≢               if lenght of m is 0 (void set) than
 :⍬⋄m              return ⍬ else return m

```

it someone know better why, and can explain this better, free of change this all... I am not so certain of this code, possible if test examples are more numerous, something will go wrong...
> 1 votes

# Answer
# Japt, 14 bytes

```
Êò2@ãX fêSÃc â

```

Try it online!

Explanation:

```
Êò2               #Get the range [2...length(input)]
   @      Ã       #For each number in that range:
    ãX            # Get the substrings of the input with that length
       fêS        # Keep only the palindromes
           c      #Flatten
             â    #Keep unique results

```
> 1 votes

# Answer
# PowerShell, 99 bytes

```
$args|% t*y|%{$s+=$_
0..$n|%{if($n-$_-and($t=-join$s[$_..$n])-eq-join$s[$n..$_]){$t}}
$n++}|sort -u

```

Try it online!

Less golfed:

```
$args|% toCharArray|%{
    $substring+=$_
    0..$n|%{
        if( $n-$_ -and ($temp=-join$substring[$_..$n]) -eq -join$substring[$n..$_] ){
            $temp
        }
    }
    $n++
}|sort -Unique

```
> 1 votes

# Answer
# Brachylog, 11 bytes

```
{s.l>1∧.↔}ᵘ

```

Try it online!

(The header in the link is broken at the time of posting, so here's the predicate (function-equivalent in Brachylog) on only the first test case, with a `w` at the end to actually print the output.)

```
               The output is
{        }ᵘ    a list containing every possible unique
 s.            substring of
               the input
   l           the length of which
    >          is greater than
     1         one
      ∧        and
       .       which
        ↔      reversed
               is itself. (implicit output within the inline sub-predicate)

```

I feel like there's a shorter way to check that the length is greater than 1. (If it didn't filter out trivial palindromes, it would just be `{s.↔}ᵘ`.)
> 1 votes

# Answer
# Stax, 10 bytes

```
îmmW┴√▄○○←

```

Run and debug it

I couldn't find an `is-palindrome` function. With that this'd probably be much shorter.
> 1 votes

# Answer
# Husk, ~~11~~ ~~9~~ 8 bytes

*Edit: -1 byte thanks to Razetime*

```
uftfS=↔Q

```

Try it online!

```
uftfS=↔Q
u               # unique elements of
       Q        # all contiguous subsets of input
 f              # after filtering to include only those that
  t             # are not a single digit/character
   f            # and then filtering to include only those that
    S=↔         # are equal to themselves reversed

```
> 1 votes

# Answer
# Thunno 2, 7 bytes

```
FœḣæḲ:U

```

Try it online!

#### Explanation

```
FœḣæḲ:U  # Implicit input
F        # All substrings of the input
 œḣ      # Filter by length > 1
   æḲ:   # Only keep palindromes
      U  # Uniquify this list
         # Implicit output

```
> 1 votes

# Answer
# Nekomata, 8 bytes

```
qNᵗz:↔=ũ

```

Attempt This Online!

```
qNᵗz:↔=ũ
q           Find a contiguous subsequence of the input
 N          Check that it is nonempty
  ᵗz        Check that it is not a singleton
    :       Duplicate
     ↔      Reverse
      =     Check equality
       ũ    Remove duplicate results

```
> 1 votes

# Answer
# Java 8, ~~202~~ ~~201~~ 199 bytes

```
import java.util.*;s->{Set r=new HashSet();String x;for(int l=s.length(),i=0,j;i<l;i++)for(j=i;++j<=l;)if((x=s.substring(i,j)).contains(new StringBuffer(x).reverse())&x.length()>1)r.add(x);return r;}

```

Try it here.

If a function isn't allowed and a full program is required, it's **~~256~~ ~~255~~ 253 bytes** instead:

```
import java.util.*;interface M{static void main(String[]a){Set r=new HashSet();String x;for(int l=a[0].length(),i=0,j;i<l;i++)for(j=i;++j<=l;)if((x=a[0].substring(i,j)).contains(new StringBuffer(x).reverse())&x.length()>1)r.add(x);System.out.print(r);}}

```

Try it here.

**Explanation:**

```
import java.util.*;      // Required import for Set and HashSet

s->{                     // Method with String parameter and Set return-type
  Set r=new HashSet();   //  Return-Set
  String t;              //  Temp-String
  for(int l=s.length(),  //  Length of the input-String
          i=0,j;         //  Index-integers (start `i` at 0)
      i<l;i++)           //  Loop (1) from `0` to `l` (exclusive)
    for(j=i;++j<=l;)     //   Inner loop (2) from `i+1` to `l` (inclusive)
      if((t=s.substring(i,j)
                         //    Set `t` to the substring from `i` to `j` (exclusive)
         ).contains(new StringBuffer(t).reverse())
                         //    If this substring is a palindrome,
         &t.length()>1)  //    and it's length is larger than 1:
        r.add(t);        //     Add the String to the Set
                         //   End of inner loop (2) (implicit / single-line body)
                         //  End of loop (1) (implicit / single-line body)
  return r;              //  Return the result-Set
}                        // End of method

```
> 0 votes

# Answer
# JavaScript (ES6), 107 bytes

Returns a Set.

```
s=>new Set((g=(s,r=[...s].reverse().join``)=>s[1]?(r==s?[s]:[]).concat(g(s.slice(1)),g(r.slice(1))):[])(s))

```

### Test cases

```
let f =

s=>new Set((g=(s,r=[...s].reverse().join``)=>s[1]?(r==s?[s]:[]).concat(g(s.slice(1)),g(r.slice(1))):[])(s))

console.log([...f('12131331').values()])
console.log([...f('3333').values()])
```
> 0 votes

---
Tags: code-golf, string, palindrome, subsequence
---


title: Sign-Swapping Sums

text:
# Question
Title: Sign-Swapping Sums
Given a nonempty list of positive integers \\$(x, y, z, \dots)\\$, your job is to determine the number of unique values of \\$\pm x \pm y \pm z \pm \dots\\$

For example, consider the list \\$(1, 2, 2)\\$. There are eight possible ways to create sums:

* \\$+ 1 + 2 + 2 \to +5\\$
* \\$+ 1 + 2 − 2 \to +1\\$
* \\$+ 1 − 2 + 2 \to +1\\$
* \\$+ 1 − 2 − 2 \to −3\\$
* \\$− 1 + 2 + 2 \to +3\\$
* \\$− 1 + 2 − 2 \to −1\\$
* \\$− 1 − 2 + 2 \to −1\\$
* \\$− 1 − 2 − 2 \to −5\\$

There are six unique sums \\$\\{5, -5, 1, -1, 3, -3\\}\\$, so the answer is \\$6\\$.

## Test Cases

```
[1, 2] => 4
[1, 2, 2] => 6
[s]*n => n+1
[1, 2, 27] => 8
[1, 2, 3, 4, 5, 6, 7] => 29
[3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] => 45
[1, 7, 2, 8, 3, 1, 6, 8, 10, 9] => 56
[93, 28, 92, 100, 43, 66, 2, 98, 2, 52, 57, 75, 39, 77, 45, 15, 13, 82, 81, 20, 68, 14, 5, 3, 72, 56, 57, 1, 23, 25, 76, 59, 60, 71, 71, 24, 1, 3, 72, 84, 72, 28, 83, 62, 66, 45, 21, 28, 49, 57, 70, 3, 44, 47, 1, 54, 53, 56, 36, 20, 99, 9, 89, 74, 1, 14, 68, 47, 99, 61, 46, 26, 69, 21, 20, 82, 23, 39, 50, 58, 24, 22, 48, 32, 30, 11, 11, 48, 90, 44, 47, 90, 61, 86, 72, 20, 56, 6, 55, 59] => 4728

```

Reference solution (optimizes for speed and not size).

If you can't handle the last case because you use a brute-force method or similar, that's fine.

## Scoring

This is , so the shortest valid solution (measured in bytes) wins.

# Answer
> 13 votes
# Wolfram Language (Mathematica), 27 bytes

```
Tr[1^Fold[#⋃+##&,{0},#]]&

```

Try it online!

Finding the number of unique sign-swapping sums is equivalent to finding the number of unique subset sums.

A proof would involve adding the sum of the input to each of the sign-swapping sums and dividing by two. Then, there's an obvious bijection.

### Explanation

```
Fold[#⋃+##&,{0},#]

```

Iterate through the input, with the initial value being `{0}`: take the union between `<current value>` and `<current value> + input element` (maps onto lists).

```
Tr[1^ ... ]

```

Golfy version of the `Length` function.

# Answer
> 8 votes
# Jelly, 6 bytes

```
ŒPS€QL

```

Try it online!

### Background

Let **L** be the input list and **{P, N}** a partition into algebraic summands with positive and negative signs. The challenge spec requires calculating **s{P,N} = sum(P) - sum(N)**.

However, since **sum(P) + sum(N) = sum(L)** and **sum(L)** does not depend on the partition, we have **s{P,N} = sum(P) - sum(N) = sum(P) - (sum(L) - sum(P)) = 2sum(P) - sum(L)**.

Thus, each unique value of **sum(P)** corresponds to one unique value of **s{P,N}**.

### How it works

```
ŒPS€QL  Main link. Argument: A (array)

ŒP      Powerset; generate all subarrays of A.
  S€    Take the sum of each.
    Q   Unique; deduplicate the sums.
     L  Take the length.

```

# Answer
> 7 votes
# MATL, ~~11~~ 10 bytes

```
nW:qBGY*un

```

Try it online! This is a port of Luis Mendo's Octave/MATLAB answer. I'm still trying to learn MATL, and I figured I'd post it, along with an explanation, since MATL is the language of the month.

### Explanation:

Here's a read-through for anyone unfamiliar with stack based programming in general, and MATL in particular.

The input vector is implicitly placed on the stack. Note that when an operation is performed on an element in the stack, then that element is removed from the stack.

```
                % Stack:
                % [1, 2, 2]
n               % Counts the number of elements of the vector on the top of the stack.
                % Stack:
                % [3]
 W              % Raise 2^x, where x is the number above it in the stack
                % Stack:
                % [8]
  :             % Range from 1...x, where x is the number above it in the stack.                    % Stack:
                % [1, 2, 3, 4, 5, 6, 7, 8]
   q            % Decrement. Stack:
                % [0, 1, 2, 3, 4, 5, 6, 7]
    B           % Convert to binary. Stack:
                % [0,0,0; 0,0,1; 0,1,0; 0,1,1; 1,0,0; 1,0,1; 1,1,0; 1,1,1]
     G          % Push input again. Stack:
                % [0,0,0; 0,0,1; 0,1,0; 0,1,1; 1,0,0; 1,0,1; 1,1,0; 1,1,1], [1; 2; 2]
      Y*        % Matrix multiplication of the two elements on the stack.
                % Stack:
                % [0; 2; 2; 4; 1; 3; 3; 5]
        u       % Keep only unique elements. Stack:
                % [0; 2; 4; 1; 3; 5]
         n      % Number of elements in the vector. Stack:
                % [6]

```

And then it outputs the final element on the stack implicitly.

# Answer
> 6 votes
# Python 2, 55 bytes

```
s={0}
for n in input():s|={t+n for t in s}
print len(s)

```

Try it online!

# Answer
> 6 votes
# Python 2, 52 bytes

```
k=1
for n in input():k|=k<<n
print bin(k).count('1')

```

Try it online!

Uses the binary representation of a number to store the reachable subset sums.

# Answer
> 5 votes
# 05AB1E, 4 bytes

```
æOÙg

```

Utilizes the same approach used in Dennis’ Jelly answer.

Try it online!

# Answer
> 5 votes
# R, ~~83~~ 75 bytes

### -8 bytes thanks to JayCe and Giuseppe

Creates a matrix of all possible combinations of (1,-1) for the size of the input vector, multiples this by the original vector to get the sums. Then unique and find the length of the result.

`function(v)nrow(unique(t(t(expand.grid(rep(list(c(1,-1)),sum(v|1)))))%*%v))`

---

### previous version:

`f=function(v)nrow(unique(as.matrix(expand.grid(rep(list(c(1,-1)),length(v))))%*%v))`

### Ungolfed with comments:

```
f=function(vector){

  List=rep(list(c(1,-1)),length(vector))   ## Create a list with length(vector) elements, all (1,-1)

  Combinations=expand.grid(Length)    ## get all combinations of the elements of the list, e.g, 1,-1,1,1,-1,1

  Matrix=as.matrix(Combinations)   ## convert to matrix

  Results=Matrix%*%vector   ## multiply the matrix original vector to get a Nx1 matrix

  Unique_results=unique(Results)   ## unique the results

  nrow(Unique_results)   ## length = number of rows of unique values
  }

```

# Answer
> 5 votes
## Haskell, 46 bytes

```
import Data.List
length.nub.map sum.mapM(:[0])

```

Try it online!

Instead of summing the subsets of the input list, we make all combinations of either keeping a number or replacing it by `0`, e.g.

```
mapM(:[0])[1,2,3] -> [[1,2,3],[1,2,0],[1,0,3],[1,0,0],[0,2,3],[0,2,0],[0,0,3],[0,0,0]]

```

This is two bytes shorter than `subsequences`.

# Answer
> 4 votes
# Pari/GP, 39 bytes

```
a->#[1|n<-Vec(prod(i=1,#a,1+x^a[i])),n]

```

Counts the number of nonzero coefficients of the polynomial \\$ \prod\_{i \in a}(1+x^i) \\$, where \\$a\\$ is the input.

Try it online!

# Answer
> 4 votes
# Octave / MATLAB, ~~45~~ ~~41~~ 40 bytes

```
@(x)nnz(unique(dec2bin(0:2^nnz(x)-1)*x))

```

Input is a column vector (using `;` as separator).

The code errors for the last test case due to memory restrictions.

This uses an idea from JungHwan Min's answer (subsets instead of alternating signs) to save a few bytes.

**Try it online!**

# Answer
> 3 votes
# Python 3, 61 bytes

```
f=lambda a,s={0}:a and f(a[1:],s|{u+a[0]for u in s})or len(s)

```

Try it online!

Recursive approach, keeping track of unique subset sums.

The real fun is that this beats `itertools` by a big margin:

## 76 bytes

```
lambda a:len({*map(sum,product(*([0,x]for x in a)))})
from itertools import*

```

Try it online!

# Answer
> 3 votes
# Pyth, 5 bytes

```
l{sMy

```

Utilizes the same approach used in Dennis’ Jelly answer.

Try it here.

# Answer
> 3 votes
# APL (Dyalog Classic), ~~12~~ 11 bytes

-1 thanks to H.PWiz

```
≢⊃(+∪⊢)/⎕,0

```

Try it online!

# Answer
> 3 votes
# Attache, 29 bytes

```
{#Unique[Flat!±_]}@Fold[`±]

```

Try it online!

This works by folding the `±` operator over the input list, then taking `±` of that list, then counting the unique atoms of the array.

Here's some examples of how the folding works:

```
Fold[`±][ [1,2] ] == 1 ± 2
                  == [1 + 2, 1 - 2]
                  == [3, -1]
Fold[`±][ [1,2,2] ] == (1 ± 2) ± 2
                    == [3, -1] ± 2
                    == [[3 + 2, 3 - 2], [-1 + 2, -1 - 2]]
                    == [[5, 1], [1, -3]]
                    == [5, 1, 1, -3]
Fold[`±][ [4,4,4,4] ] == (4 ± 4) ± 4 ± 4
                      == [8, 0] ± 4 ± 4
                      == [[12, 4], [4, -4]] ± 4
                      == [[[16, 8], [8, 0]], [[8, 0], [0, -8]]]
                      == [16, 8, 8, 0, 8, 0, 0, -8]
                      == [16, 8, 0, -8]

```

Then we generate all permutations of the final sign by applying PlusMinus once more.

## A more efficient version, 31 bytes

```
`#@(q:=Unique@Flat@`±)@Fold[q]

```

Try it online! This doesn't time out on the final test case, since it doesn't generate unnecessary combinations.

# Answer
> 3 votes
# , 62 bytes

```
function(V)sum(unique(c(V%*%combn(rep(0:1,L),L<-sum(V|1))))|1)

```

Try it online!

Ports Dennis' algorithm. It's closest to the Octave/MATL answers as it uses a similar bitmap and matrix product for inclusion/exclusion of terms.

# Answer
> 2 votes
# Perl 5 `-p`, 39 bytes

```
s/^| /{+,-}/g;$_=grep!$s{eval$_}++,glob

```

Try it online!

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

```
f=([c,...a],s=n=!(o={}))=>c?f(a,s-c)|f(a,s+c)&&n:o[s]=o[s]||++n

```

Try it online!

# Answer
> 2 votes
# Husk, 5 bytes

```
LumΣṖ

```

Try it online!

Port of Dennis' Jelly answer.

### Explanation

```
LumΣṖ                     [1,2,2]
    Ṗ  Powerset           [[],[1],[2],[1,2],[2],[1,2],[2,2],[1,2,2]]
  mΣ   Sum each           [0,1,2,3,2,3,4,5]
 u     Remove duplicates  [0,1,2,3,4,5]
L      Length             6

```

# Answer
> 2 votes
# Perl 6, 33 bytes

```
{+set ([X](^2 xx$_)XZ*$_,)>>.sum}

```

Try it online!

# Answer
> 2 votes
# Bash \+ GNU utilities, 49 bytes

```
eval echo "{,-}${@//,/{+,-\}}\;"|bc|sort -u|wc -l

```

Try it online!

Input given as a comma-separated list at the command-line.

### Explanation

```
               ${@//,/{+,-\}}                      # Replace commas with {+,-}
          "{,-}${@//,/{+,-\}}\;"                   # Build a brace expansion with {+,-} before every number and ; at the end
eval echo "{,-}${@//,/{+,-\}}\;"                   # Expand to give every combination expression, separated by ;
                                |bc                # Arithmetically evaluate each line
                                   |sort -u        # Remove duplicates
                                            wc -l  # Count

```

# Answer
> 2 votes
# C (gcc), ~~74~~ 69 bytes

```
f(a,b)int*a;{long k=1;for(;b--;k|=k<<a[b]);a=__builtin_popcountl(k);}

```

Try it online!

C port of @xnor's answer

# Answer
> 2 votes
# x86\_64 machine language for Linux, ~~31~~ 29 bytes

```
 0:   31 d2                   xor    %edx,%edx
 2:   6a 01                   pushq  $0x1
 4:   58                      pop    %rax
 5:   8b 0c 97                mov    (%rdi,%rdx,4),%ecx
 8:   48 89 c3                mov    %rax,%rbx
 b:   ff c2                   inc    %edx
 d:   48 d3 e3                shl    %cl,%rbx
10:   48 09 d8                or     %rbx,%rax
13:   39 d6                   cmp    %ese,%edx
15:   7c ee                   jle    5 <+0x5>
17:   f3 48 0f b8 c0          popcnt %rax,%rax
1c:   c3                      retq

```

Try it online!

Inspired by @xnor's answer. Requires a machine with the `POPCNT` instruction.

# Answer
> 1 votes
# APL (Dyalog Classic), ~~34~~ ~~33~~ 32 bytes

```
{≢∪⍵+.×⍨↑{,⍵∘.,U}⍣(≢1↓⍵)⊢U←¯1 1}

```

Try it online!

Thanks to @ngn for -1 byte!

# Answer
> 1 votes
# Clean, 82 bytes

```
import StdEnv
f[]=length
f[h:t]=f t o foldr(\e l=removeDup[e+h,e-h:l])[]
?l=f l[0]

```

Try it online!

Defines the function `? :: [Int] -> Int` using `f :: [Int] -> ([Int] -> Int)` as a helper to reduce over each possible sum after an addition or subtraction.

# Answer
> 1 votes
# Java 8, ~~207~~ ~~83~~ 44 bytes

```
s->Long.bitCount(s.reduce(1L,(r,c)->r|r<<c))

```

Port of @xnor's Python 2 answer.
-39 bytes thanks to *@Jakob*.

Try it online.

```
s->               // Method with Long-Stream parameter and long return-type
  Long.bitCount(  //  Return the amount of 1s in the binary representation of:
    s.reduce(1L,  //   Result-Long, starting at 1
     (r,c)->      //   Loop pair-wise (result,current):
      r|          //    Bitwise-OR the result `r` with:
        r<<c))    //    result `r` bitwise left-shifted by the current `c`

```

# Answer
> 1 votes
# APL (Dyalog Classic), 21 bytes

```
⍴∘∪⊢+.×1-2×2(⍴⍨⊤∘⍳*)⍴

```

Try it online!

## Explanation

```
2(⍴⍨⊤∘⍳*)⍴

```

A function train equivalent to `{((⍴⍵)⍴2)⊤⍳(⍴⍵)}`, which generates a matrix that has the binary representations of 0 to the length of the input as columns

```
1-2×

```

Maps `1`s to `-1`s and `0`s to `1`s

```
⊢+.×

```

Matrix multiplication with the input, which gives an array of all possible sums

```
⍴∘∪

```

Remove duplicates, then count

# Answer
> 1 votes
# Java 8, 85 bytes

Another Java port of *xnor*'s answer. Like the original answer, this uses an arbitrary-precision bitmap so that there's no upper limit on the size of a subset sum.

It's a lambda from a sequential `java.util.stream.Stream<Integer>` to `int`.

```
s->s.reduce(java.math.BigInteger.ONE,(a,e)->a.or(a.shiftLeft(e)),(u,v)->u).bitCount()

```

Try It Online

Note that the combiner (the third argument to `reduce`) is unused since the stream is sequential. The function I chose is arbitrary.

# Answer
> 1 votes
# Julia 0.6, 54 52 bytes

```
V->(~W=W==[]?0:∪([n=W[] -n].+~W[2:end]))(V)|>endof

```

Try it online!

(*-2 bytes by replacing `¬` with `~`, thanks to Jo King*)

Works for all test cases. Makes use of broadcast to collect all possible sums, then counts them.

Explanation:

```
function g_(V)
  function inner(W)  #named ~ in golf version to save bytes
    W == [] ? 0 :    #return 0 when input empty (base case)
    ∪(               #unique elements of
      [n=W[] -n]     #take the first element and its negation
      .+             #broadcast-add that to each element of
      inner([2:end]) #sign-swapping sums of the rest of the array
     )
  end                #returns the list of unique elements out of those sums
  return endof(inner(V)) #return the length of that list
end

```

---

Older solution:

# Julia 0.6, 64 bytes

```
N->endof(∪([2(i&2^~-j>0)-1 for i=0:~-2^(l=endof(N)),j=1:l]*N))

```

Try it online!

Works for input arrays with length upto 63 (so doesn't work for the last test case, which is fine according to OP).

Explanation:

```
function f_(N)
  endof(                            #length of
        ∪(                          #unique elements of
          [
           (i & 2^(j-1) > 0)        #check j'th bit (from right) of i
           * 2 - 1                  #convert bit value from (0,1)=>(-1,1)
           for i = 0:2^endof(N)-1,  #where i is numbers 0 to 2^length(N)-1
           j = 1:endof(N)           #and j is 1 to length(N) (i.e. the bits in i)
          ]                         #so we have a matrix [-1 -1 -1;1 -1 -1;1 -1 1;...]
          *                         #matrix multiply that with the input array,
          N                         #thus calculating different combinations of
         ))                         #sign-swapping sums
end

```

# Answer
> 1 votes
# Desmos, ~~90~~ 74 bytes

*-16 bytes thanks to Aiden Chow*!

```
f(A)=unique(∑_{j=1}^a(-1)^{floor([0...2^a]2/2^j)}A[j]).length
a=A.length

```

Try it on Desmos!

Brute-forces all possible sums; then counts the number of distinct sums.

The exact choice of `+` or `-` is encoded in the binary digits of `i`, ignoring the zeroth bit because Desmos arrays are 1-indexed.

# Answer
> 0 votes
# JavaScript (Babel Node), 64 bytes

```
F=([f,...r],s=[0])=>f?F(r,s.flatMap(x=>[x+f,x])):new Set(s).size

```

Try it online!

This won't work for last testcase.

---

More effective solution (works on last testcase):

# JavaScript (Babel Node), 71 bytes

```
F=([f,...r],s=[0])=>f?F(r,[...new Set(s.flatMap(x=>[x+f,x]))]):s.length

```

Try it online!

---

This won't work in a real browser due to `Array#smoosh`.

Thanks to Bubbler, `[x+f,x-f]` -\> `[x+f,x]` saves 2 bytes.

# Answer
> 0 votes
# Red, 73 bytes

```
func[b][s:[0]foreach n b[foreach m s[s: union s reduce[m + n]]]length? s]

```

Port of Dennis' Python 2 answer. Does not handle the last test case.

Try it online!

# Answer
> 0 votes
# Japt, 9 bytes

Saved 1 byte thanks to @Shaggy

```
à mx â ÊÄ

```

Try it online! This is a slightly modified port of Dennis' Jelly answer, credits to him for the idea. Explanation:

```
à             Take all non-empty subsets of the input array
  mx           and sum them
     â Ê      Return the amount of unique sums
        Ä      plus one (to account for the non-empty subset)

```

# Answer
> 0 votes
# Stax, 12 bytes

```
Çσ▓╥7Cφ1╝╥ò1

```

Run and debug it

Doesn't handle the last test case in acceptable time.

Explanation (unpacked):

```
0]s{cN\{+K$uF% Full program, implicit input
0]s            Put [0] under input (array of sums)
   {        F  Foreach:
    cN\          x -> [x, -x]
       { K       Cartesian join:
        +          Add
          $u     Flatten and unique
             % Length
               Implicit output

```

# Answer
> 0 votes
# C (gcc), ~~236~~ ~~208~~ 204 bytes

* Saved ~~twenty-eight~~ thirty-two bytes thanks to ceilingcat.

```
*s,i,g,n;S(w,a,p,_)int*p,*w;{if(_-a)for(_[p]=2;_[p]--;)S(w,a,p,-~_);else{for(*s=0,i=a;i--;)*s+=~(p[i]*2)*w[i];s++;}}f(w,a)int*w;{int p[a+1],r[g=1<<a];s=r;for(S(w,a,p,n=0);g--;wmemchr(r,r[g],g)||++n);w=n;}

```

Try it online!

# Answer
> 0 votes
# Retina, 27 bytes

```
+`\d+ ?
*@$%"$&*
%O`.
D`
.+

```

Try it online!

## Explanation

```
+`\d+ ?
*@$%"$&*

```

For each number, remove the space after it if there is one,. Then split the line into two, one with the number replaced with that many `@`s, and another with the number replaced with that many `_`s. Loop until no more numbers exist. That generates all combination, albeit with some duplicates.

```
%O`.

```

For each line, sort the characters. With this, there is a 1-1 correspondence between a sum and this "`@_`" representation.

```
D`

```

Deduplicate the lines.

```
.+

```

Count the non-empty lines.

# Answer
> 0 votes
# Thunno 2 `L`, 3 bytes

```
ʠʂU

```

Try it online!

#### Explanation

```
ʠʂU  # Implicit input
ʠ    # Powerset
 ʂ   # Sum each
  U  # Uniquify
     # Length
     # Implicit output

```

# Answer
> 0 votes
# Nekomata \+ `-n`, 3 bytes

```
ŋ∑ũ

```

Attempt This Online!

```
ŋ∑ũ
ŋ       Non-deterministically negate some elements of the input
 ∑      Sum
  ũ     Unique values

```

`-n` counts the number of possible outputs.

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


title: Efficient counting

text:
# Question
Title: Efficient counting
When I was a kid, and wanted to count the dollar bills in my life savings, I would count out loud:

> one, two, three, four, five, six, seven, eight, nine, ten;
> eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty;
> twenty-one, twenty-two, twenty-three, twenty-four, twenty-five...

Eventually I got tired of pronouncing each of these multi-syllable numbers. Being mathematically minded, I created a much more efficient method of counting:

> one, two, three, four, five, six, seven, eight, nine, ten;
> one, two, three, four, five, six, seven, eight, nine, twenty;
> one, two, three, four, five, six, seven, eight, nine, thirty...

As you can see, I would only pronounce the digit(s) that have changed from the previous number. This has the added advantage that it's considerably more repetitive than the English names for numbers, and therefore requires less brainpower to compute.

## Challenge

Write a program/function which takes in a positive integer and outputs/returns how I would count it: that is, the right-most non-zero digit and all trailing zeroes.

### Examples

```
   1    1
   2    2
  10   10
  11    1
  29    9
  30   30
  99    9
 100  100
 119    9
 120   20
 200  200
 409    9
1020   20

```

A full list of test-cases shouldn't be necessary. This is A274206 on OEIS.

## Rules

* Your entry must theoretically work for all positive integers, ignoring precision and memory issues.
* Input and output must be in decimal.
* You may choose to take input and/or output as a number, a string, or an array of digits.
* Input is guaranteed to be a positive integer. Your entry can do anything for invalid input.

This is , so **the shortest code in bytes wins.**

# Answer
# Python 2, 28 bytes

```
f=lambda n:n%10or 10*f(n/10)

```

Try it online!

A recursive formula works out very cleanly. If the last digit is nonzero, output it. Otherwise, remove the final zero, compute the output for that, and multiply it by 10.
> 20 votes

# Answer
# Jelly, ~~6~~ 3 bytes

-3 bytes by having I/O as a decimal list of digits.

```
ṫTṪ

```

Test suite at **Try it online!**

### How?

```
ṫTṪ - Main link: listOfDigits  e.g.  [1,    0,    2,    0]  or [1,      1,    9  ]
 T  - truthy indexes                 [1,          3      ]     [1,      2,    3  ]
ṫ   - tail (vectorises)              [[1,0,2,0],  [2,0]  ]     [[1,1,9],[1,9],[9]]
  Ṫ - tail pop                                    [2,0]                       [9]

```

---

If we could not take decimal lists a 6 byter is:

```
DµṫTṪḌ

```

Which you can see **here**.

This does the same thing, but converts an integer to a decimal list beforehand and converts back to an integer afterwards.
> 11 votes

# Answer
# C, ~~30~~ ~~29~~ 27 bytes

Proud of this as I abuse two C exploits to golf this up (described at end of post); This is specifically for C (GCC)

---

3) `b=10;f(a){a=a%b?:b*f(a/b);}`//27 bytes

2) ~~`b;f(a){b=a=a%10?:10*f(a/10);}`~~ //29 bytes

1) ~~`f(i){return i%10?:10*f(i/10);}`~~ //30 bytes

Try it online (27 byte version)

---

First attempt (30 bytes): Abuses the fact that in GCC if no value is declared in ternary, the conditional value will be returned. Hence why my ternary operator is blank for the truth return value.

Second attempt (29 bytes): Abuses **memory bug** in GCC where, as far as I understand, if a function has no return value, when more than two variables have been meaningfully utilized in the function, the last set value of the first argument variable will be returned.
*(Edit: but this "set value" must set in certain ways, for example setting a variable with `=` or `+=` works but setting it with `%=` does not work; weird)*

Third attempt (27 bytes): Since I must meaningfully utilize the second variable (b) anyways to properly abuse the memory bug mentioned above, I may as well use it as an actual variable for "10" for substitution.
*(Note: I should be able to swap `a=a%b` with `a%=b` to save another byte but unfortunately this causes the memory bug exploit above to stop "working", so I can't)*
> 9 votes

# Answer
# Retina, ~~7~~ 6 bytes

```
!`.0*$

```

**Try it online** (all test cases)

Output matches of a digit followed by any zeros at the end of the input string. Though not required, this also happens to work for `0`.
> 7 votes

# Answer
# Cubix, 18 ~~32~~ bytes

~~I think I'll have to spend sometime on this later and see if I can compress it a bit. But for the moment here it is.~~
Turns out I was thinking about this totally the wrong way. Now the process incrementally applies a mod (1,10,100,1000,...) to the input integer and prints out the first one which isn't zero. Bit more boring, but shorter.

```
!N%*I1^\.u;u@O\;;r

```

Try it here

```
    ! N
    % *
I 1 ^ \ . u ; u
@ O \ ; ; r . .
    . .
    . .

```
> 7 votes

# Answer
## Javascript ~~19~~ 18 bytes

Thanks to ETHproductions for golfing off one byte and Patrick Roberts for golfing off two bytes

```
x=>x.match`.0*$`

```

Returns an array of strings that match the regex of being at the end of the input string with any character followed by the largest possible number of zeroes.

Try it Online
> 5 votes

# Answer
## JavaScript, 21 bytes

```
f=n=>n%10||10*f(n/10)

```

### Test cases

```
f=n=>n%10||10*f(n/10)

console.log(f(1   )); //  1
console.log(f(2   )); //  2
console.log(f(10  )); //  10
console.log(f(29  )); //  9
console.log(f(99  )); //  9
console.log(f(1020)); //  20
```
> 5 votes

# Answer
# Brachylog, 2 bytes

```
a₁

```

Try it online!

The suffix builtin `a₁`, for integers, is implemented as:

```
brachylog_adfix('integer':1, 'integer':0, 'integer':0).
brachylog_adfix('integer':1, 'integer':I, 'integer':P) :-
    H #\= 0,
    H2 #\= 0,
    abs(P) #=< abs(I),
    integer_value('integer':Sign:[H|T], I),
    integer_value('integer':Sign:[H2|T2], P),
    brachylog_adfix('integer':1, [H|T], [H2|T2]).

```

Brachylog likes to be able to treat integers as lists of digits, and for that it uses the custom utility predicate `integer_value/2`. The interesting thing about `integer_value/2` here is that since it has to be able to correctly translate a digit list with leading zeros, it ends up also being able to translate an integer to a digit list with leading zeros, so predicates that don't want that to happen (most of them, *especially* the nondet ones like `a`) forbid the heads of their digit lists from being 0. So, while `a₁` generates suffixes shortest first for lists and strings, it skips over any suffix of an integer with a leading 0, which in addition to removing duplicates, also means that the first suffix generated is the rightmost non-zero digit with all trailing zeroes.
> 5 votes

# Answer
# Bash + coreutils, 12

```
grep -o .0*$

```

Try it online.
> 3 votes

# Answer
## Grime, 5 bytes

```
d\0*e

```

Try it online!

## Explanation

```
       Find the longest substring of the input matching this pattern:
d      a digit, then
 \0*   zero or more 0s, then
    e  edge of input (which is handled as an Nx1 rectangle of characters).

```
> 3 votes

# Answer
# Brain-Flak, 74 bytes

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

```

Try it online!

Only prints the last non-0 and all trailing 0s.

**Explanation:**

```
{({}<>)<>}                    # Move everything to the other stack (reverse the input)
(())                          # Push a 1 to get started
{                             # do...
  {}<>                        #   pop the result of the equals check (or initial 1)
  (                           #   push...
    ({}<>)                    #     the top value from the other stack (also put this on the stack)
    [((((()()()){}){}){}){}]  #     minus the ASCII value of 0
    <(())>                    #     on top of a 1
  )                           #   close the push
  {                           #   if not zero (ie. if not equal)
    ((<{}{}>))                #     replace the 1 from 3 lines back with a 0
  }{}                         #   end if and pop the extra 0
}                             # while the copied value != "0"
{}                            # pop the result of the equals check

```
> 2 votes

# Answer
# Vim, 19 bytes

Two versions, both 19 bytes:

```
:s/\v.*([^0]0*)/\1
:s/.*\([^0]0*\)/\1

```

Plus a trailing carriage return on each.

Verify all test-cases online! (One byte added to test on multiple lines)
> 2 votes

# Answer
# TI-Basic, 18 bytes

```
If fPart(.1Ans
Return
Ans.1
prgmA
10Ans

```
> 2 votes

# Answer
# R, 33 bytes

Implemented as an unnamed function

```
function(x)rle(x%%10^(0:99))$v[2]

```

This applies a mod of 10^0 through 10^99. `rle` is used to reduce the results down so that the second item is always the result we want.
Try it online!
> 2 votes

# Answer
# Zsh, ~~18~~ 16 bytes

```
<<<${(M)1%[^0]*}

```

~~Try it online!~~ Try it online!

# Bash, ~~25~~ 20 bytes

***-5 bytes** by @roblogic*

```
echo ${1#${1%[^0]*}}

```

Try it online! ~~Try it online!~~

--- Shells need to call external programs to use regex, so we have to make do with globbing.

The `${1%[^0]*}` expansion matches the shortest suffix beginning with a nonzero character, and removes it.

* In Zsh, adding the `(M)` flag causes the matched suffix to be kept instead of removed.
* In Bash, the `${1% }` expansion removes as a prefix whatever is left.
> 2 votes

# Answer
## GNU sed, ~~17~~ 14 + 1(r flag) = 15 bytes

**Edit:** 2 bytes less thanks to Riley

```
s:.*([^0]):\1:

```

It works by deleting everything until the right-most nonzero digit, which is then printed along with any existing trailing zeros. The script can handle multiple tests in one run, each on a separate line.

**Try it online!** (all test examples)
> 1 votes

# Answer
# MATL, ~~10~~ 7 bytes

*3 bytes saved thanks to @B. Mehta!*

```
tfX>Jh)

```

Input and output are an array of digits.

Try it online!

Or verify all test cases.

### Explanation

```
t     % Input string implicitly. Duplicate
f     % Push indices of non-zero digits
X>    % Keep maximum, say k
Jh    % Attach 1j to give [k, 1j]. This is interpreted as an index "k:end"
)     % Index into original string. Display implcitly

```
> 1 votes

# Answer
## Mathematica, 26 bytes

Pure function which takes a list of digits and outputs a list of digits:

```
#/.{___,x_,y:0...}:>{x,y}&

```

## Explanation

```
#                           First argument
 /.                           Replace
   {                              start of list followed by
    ___,                          zero or more elements followed by
        x_,                       an element (referred to later as x) followed by
           y:0...                 a sequence of zero or more 0s (referred to later as y) followed by
                 }                end of list
                  :>            with
                    {x,y}         {x,y}
                         &   End of function.

```

This works since it finds the leftmost match for `x`, which must be the rightmost nonzero element of the list since it is followed by a sequence of zero of more `0`s and then the end of the list.
> 1 votes

# Answer
# Java 8, 47 bytes

this is a lambda expression assignable to a `IntUnaryOperator`:

```
x->{int m=1;for(;x%m<1;m*=10);return x%m*m/10;}

```

explanation: multiply m by 10 until `x%m` is not 0. `return x%m*m/10` requires the division because m is an order of magnitude more than the desired result.
> 1 votes

# Answer
# Perl 6, 10 bytes

```
{+m/.0*$/}

```

Trivial regex solution. Inputs and outputs a number.
> 1 votes

# Answer
# C#, ~~30~~ 28 bytes

Based on this JavaScript answer, so I suppose all the credits kinda go to him.

## Golfed

```
i=a=>a%10<1?10*i(a/10):a%10;

```
* -2 bytes by removing `()` around `a` thanks to Emigna
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
RD0Ê1k>£R

```

Try it online! or as a Test suite

**Explanation**

```
R          # reverse input
 D         # duplicate
  0Ê       # check each for inequality with 0
    1k     # get the index of the first 1
      >    # increment
       £   # take that many digits from the input
        R  # reverse

```
> 1 votes

# Answer
# J, 27 bytes

```
10&|`(10*(p%&10))@.(0=10&|)

```

It's based off of xnor's formula, so credits to him.
> 1 votes

# Answer
# Kotlin, 49 bytes

lambda, assignable to `(List<Int>) -> List<Int>`

```
{a->a.slice(a.indexOfLast{it in 1..9}..a.size-1)}

```
* implicit parameter name `it` in `indexOfLast`
* `..` for building ranges
> 1 votes

# Answer
# Perl 5, 12 bytes

11, plus 1 for `-nE` instead of `-e`

```
say/(.0*$)/

```
> 1 votes

# Answer
# Japt, 6 bytes

```
f".0*$

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
æΩ$3╚

```

Run and debug it

### Procedure:

1. Calculate "multiplicity" by 10. (That's the number of times 10 evenly divides the input)
2. Add 1.
3. Keep that many characters from the right of (the input as a string).
> 1 votes

# Answer
# 05AB1E, 4 bytes

```
ĀÅ¡θ

```

I/O as a list of digits.

Try it online or verify all test cases (test suite contains a join for better readability).

**Explanation:**

```
Ā     # Python-style truthify each digit in the (implicit) input-list (0 if 0; 1 if [1-9])
      #  i.e. [9,0,4,0,3,0,0] → [1,0,1,0,1,0,0]
 Å¡   # Split the (implicit) input-list on truthy values (1s)
      #  i.e. [9,0,4,0,3,0,0] and [1,0,1,0,1,0,0] → [[],[9,0],[4,0],[3,0,0]]
   θ  # And only leave the last inner list
      #  i.e. [[],[9,0],[4,0],[3,0,0]] → [3,0,0]
      # (after which it is output implicitly as result)

```
> 1 votes

# Answer
# Thunno 2 `t`, 3 bytes

```
V€ỵ

```

Try it online!

Port of Jonathan Allan's Jelly answer.

#### Explanation

```
V€ỵ  # Implicit input
V    # Truthy indices
 €ỵ  # Head remove over each
     # Take the last item
     # Implicit output

```
> 1 votes

# Answer
# Desmos, 62 bytes

Input (variable `A`) and output (variable `B`) are both arrays of digits. Run the ticker to start the program.

**Ticker:**

```
B->join(A[n],B),n->\left\{A[n]=0:n-1,0\right\}

```

**Expression List:**

```
B=[]
n=A.length

```

Try it on Desmos!

Scans `A` from right to left until a nonzero digit is encountered. Afterwards, set `n=0` to invalidate the action and halt the program.
> 1 votes

# Answer
# Rust, 34 bytes

```
|n|n[n.rfind(|d|d!='0')?..].into()

```

If I knew a way to use impl traits on closures, I could remove 7 bytes from `.into()`, but It doesn't seem like that's allowed on `fn pointers` or `Fn` objects.

Rust Playground
> 1 votes

# Answer
# Vyxal, 3 bytes

```
Ttȯ

```

Try it Online!

Port of Jelly.

## Explained

```
Ttȯ
T    # Truthy indices of the input.
 t   # Last item of that
  ȯ  # input[that:]

```

Created with the help of Luminespire.
> 1 votes

# Answer
# , 11 bytes

```
}.~_1{I.@:*

```

Port of Jelly. Takes a digit list.

Attempt This Online!

```
}.~_1{I.@:*
      I.@:*  NB. indices of positive numbers
   _1{       NB. tail
}.~          NB. drop that many items

```
> 1 votes

# Answer
## Pyke, ~~13~~ ~~11~~ 10 bytes

```
`1QY0mN%e>

```

Try it here!

```
  QY       -     digits(input)
    0mN    -    map(^, i != 0)
 1     %   -   indecies(^, i == 1)
        e  -  ^[-1]
`        > - str(input)[^:]

```

### 11 bytes:

```
`D\0mN1R%e>

```

Try it here!

### 13 bytes:

```
`D\0mN_1R@_t>

```

Try it here!
> 0 votes

# Answer
**Haskell 57 Bytes**

```
f(x:s)a|x=='0'=f s$'0':a|1>0=x:a
t x=f(reverse.show$x)[]

Input    -> Output
t 120    -> "20"
t 30200  -> "200"

```
> 0 votes

# Answer
## Batch, 88 bytes

```
@set/ps=
@set z=
:l
@if %s:~-1%==0 set z=0%z%&set s=%s:~,-1%&goto l
@echo %s:~-1%%z%

```

Takes input on STDIN.
> 0 votes

# Answer
## Ruby, 14 bytes

```
->n{n[/.0*$/]}

```

Input is a string (allowed by the rules)
> 0 votes

# Answer
# Haskell, 38 bytes

```
x!d|m<-mod x d,m>0=m|e<-10*d=x!e
(!10)

```

Try it online! Usage: `(!10) 1020` yields `20`.

**Explanation:**

`x!d` is a recursive formula which computes `x` modulo `d` with initially `d=10`. If the result is larger zero it is returned, otherwise recursively `x!(10*d)` is called.

**Other approaches:** (39 bytes)

```
x!d|m<-x`mod`10^d,m>0=m|e<-1+d=x!e;(!1)
f x=[y|y<-[x`mod`10^e|e<-[1..]],y>0]!!0
f x=[y|y<-map(mod x.(10^))[1..],y>0]!!0

```
> 0 votes

# Answer
# Java 8, 33 bytes

```
s->s.replaceAll(".*?(.0*)$","$1")

```

I/O as a String.

Try it online.

**Explanation:**

```
s->                         // Method with String as both parameter and return-type
  s.replaceAll(".*?(.0*)$", //  Replace all occurrences of this match,
               "$1")        //  with this replacement

```

*Regex explanation:*

```
.*?(.0*)$                   // MATCH:
.*?                         //  Zero or more optional characters
                            //  (the optional is used to give other 0+ matches
                            //   higher priority/precedence)
    .                       //  Followed by any character
     0*                     //  Followed by zero or more literal 0s
        $                   //  At the end of the string
   (   )                    //  And capture those non-optional characters in capture group 1

$1                          // REPLACEMENT:
                            //  The content of capture group 1, which basically removes
                            //  the optional characters outside the capture group

```
> 0 votes

---
Tags: code-golf, number
---


# Question
Title: Output with the same number of digits of pi as the length of the code
Your challenge is to print `x` digits of pi where `x` is your code length.

Examples:

```
Source code (length) -> output
foo!        (4)         3.141
foobar      (6)         3.14159
kinda long  (10)        3.141592653
+++++       (5)         3.1415
123456789   (9)         3.14159265

```

You can use `floor(π/10 * 10<sup>code_length</sup>) / 10<sup>code_length - 1</sup>` to determine the number of digits you need to print. Note that the decimal point does not count as a digit of pi - so code of length 3 should have output `3.14`, of length 4.

Rules:

* Your code length must be larger than three characters.
* You may not use any standard loopholes.
* You may use any standard allowed output methods.
* You may not read your source to determine code length.
* **You may not use a builtin pi constant.**
* Pi must be *completely accurate* and not approximated.
* The decimal point in the output is necessary. If you choose to output via return value, you must return a floating point integer.
* The goal of this challenge is to find the shortest solution in each language, not the shortest language for the solution. Don't be afraid to post a solution in a language when a shorter solution is posted in the same language as long as your solution uses a different method.

# Answer
> 3 votes
# Japt, ~~9~~ 4 bytes

As short as it can allowably get :)

Includes an unprintable (reverse line feed, charcode 141) after the `#`.

```
3.#

```

Test it

In Japt, any character following `#` is converted to its character code and appended to any digits or decimal points which may precede it, in this case the `3.`

# Answer
> 8 votes
# Mathematica, 18 bytes

using zeta function

```
Sqrt[6Zeta@2]~N~18

```

Try it online!

# Answer
> 7 votes
# Jelly, 9 bytes

```
“Œı⁸Ç’÷ȷ8

```

Try it online!

Outputs `3.14159265`

**How it Works**

```
“Œı⁸Ç’     - The integer 314159265
      ÷    - divide
       ȷ8  - The integer 100000000

```

# Answer
> 6 votes
# Jelly, 6 bytes

```
3;⁽4ƒṾ

```

**Try it online!**

Prints `3,14159` with the allowed "European" decimal separator, `,`.

### How?

```
3;⁽4ƒṾ - Main link: no arguments
3      - literal 3                3
  ⁽4ƒ  - base 250 literal 14159   14159
 ;     - concatenate              [3,14159]
     Ṿ - unevaluate               ['3', ',', '1', '4', '1', '5', '9']
       - implicit print           3,14159

```

# Answer
> 6 votes
# VBA (Excel), 15 bytes

```
MsgBox 4*Atn(1)

```

Output: 3.14159265358979

I think this is not acceptable as I golfed it just to fit the length of the PI. The un-golfed length of it is 17 bytes. D:

# Answer
> 4 votes
# Python 3, 64 bytes

```
print("3.%d"%int("SIXW57LUPVBUA10HBQJOL57QLF54UT0U00KIN32O",36))

```

Try it online!

# Answer
> 4 votes
# Desmos, 130 bytes

```
f\left(\right)=\frac{\operatorname{floor}\left(10^{128}\cdot 4\sum_{k=1}^{9^9}\frac{\left(-1\right)^{k+1}}{2k-1}\right)}{10^{128}}

```

The source code for this (Which can be accessed by copy and pasting inside and outside of Desmos) isn't optimal when generated using the Desmos editor, so a few bytes of whitespace were golfed down where possible.

This defines a function `f` which takes no arguments returns pi, calculated using the Gregory Sequence to `k=9^9` *(I can't confirm this is accurate enough, however I am of the believe that it is, it can be made more accurate with a greater value of k)* it then floors the result to `128` decimal places, which, alongside the `3.`, is the length of the source code.

Try it online!

# Answer
> 4 votes
# SOGL V0.12, ~~10~~ ~~9~~ 7 bytes

```
4ΘΞ“6⌡υ

```

Try it Here!

Explanation:

```
4ΘΞ“     push 31415
    6⌡   6 times do
      υ    divide by 10

```

# Answer
> 4 votes
# CJam, 5 bytes

```
3.14F

```

Try it online!

### How it works

```
3.14   e# Push 3.14.
    F  e# Push 15.

```

# Answer
> 3 votes
# Charcoal, 8 bytes

```
”i‴Ａχ:&”

```

Try it online!

Just a compressed string.

# Answer
> 3 votes
# Javascript, 16 bytes

```
_=>Math.acos(-1)

```

```
f=
_=>Math.acos(-1)
console.log(f())
```

# Answer
> 3 votes
# Neim, 5 bytes

```
3FBρσ

```

Explanation:

```
3      Push 3
 FB    F pushes 45, B converts it into a character code, '.'
   ρ   Push 14
    σ  Push 15
Implicitly concatenate and print stack

```

Try it online!

# Answer
> 3 votes
# APL, 6 bytes

```
10○⍟-1

```

Takes the imaginary part of ln(-1).

Try it online!

# Answer
> 2 votes
# , 16 bytes

```
17j15":4*_3 o.1:

```

Try it online!

Similar to the VBA answer. Outputs: `3.141592653589793`.

# Answer
> 2 votes
# Math.JS, 17 bytes.

```
     log(-1,e).im

```

*That's 5 leading spaces*

This calculates to 15 decimal places, and implicitly prints it.

Try It Online!

# Answer
> 2 votes
# 05AB1E, 11 bytes

```
3•∊&SK•)'.ý

```

Try it online!

```
COMMAND     # CURRENT STACK         | EXPLANATION
------------#-----------------------+-----------------------------------
3           # [3]                   | Push 3.
 •∊&SK•     # [3, 1415926535]       | Push compressed base-255 number 1415926535.
       )    # [[3,1415926535]]      | Wrap the 2 to an array.
        '.  # [[3,1415926535],'.']  | Push a decimal point.
          ý # ['3.1415926535']      | Join 3 and 1415926535 with a decimal point.

```

---

***USING BUILT-INS:***

# 05AB1E, 4 bytes

```
žq5£

```

Try it online!

---

`3žs` doesn't work for some reason...

# Answer
> 2 votes
# Jelly, 6 bytes

```
-ÆAær5

```

Try it online!

Uses a different approach than the other Jelly answers.

## How?

`-ÆA` is inverse cosine of `-1` (which is pi), `ær5` retrieves the needed section. It worked out so rounding is equivalent to truncation in this case

# Answer
> 2 votes
# ForceLang, 269 bytes

```
set S 0x5F258E476FC1B3B5571012206C637089460E41E814CB071E61431B5F0671F551D18D2C5D2D3A2565E408C6DE8D753F595B6E9979C3866D1C9965008DCFB02E3BD11D21DFFAF17978F05C8BBACF55A5ED5E90B1D8CAD8736AA4B728EB342B453F86353DB371D322B6A98613BC5CCB00AC2.mult 1e-270
io.write S.toString 268

```

# Answer
> 2 votes
# MATL, ~~9~~ 8 bytes

```
-1X;V9:)

```

Try it online!

Explanation:

```
-1      % number literal
X;      % inverse cosine (radians), giving pi
V       % convert to string
9       % specify precision
:)      % keep first 9 characters - 8 digits of precision

```

Saved one byte thanks to Luis Mendo!

# Answer
> 2 votes
# RPL (HP48), 86.5 bytes, 87 digits \[Does this count?\]

```
« GROB 8 43
14159265358979323846264338327950288419716939937510582097494459230781640628620899862803
→STR 9 OVER SIZE SUB 2 "." REPL »

```

GROB is an image keyword. The 2 numbers that follow are width and height. The hexadecimal digits that follow are bitmap. That's 1 byte of storage for every 2 digits plus the image metadata.

Empty program `« »` takes 10 bytes. A command takes 2.5 bytes. A float takes 10.5 bytes, but if it's equal to a single digit integer, it can take 2.5 bytes.

HP48 stores 4 rather than 8 bits at each memory location, so a byte occupies 2 consecutive locations (low endian). Often 20-bit chunks are used, and they do take 2.5 bytes (not 3).

# Answer
> 2 votes
# TI-BASIC, 7 bytes

```
round(4tan⁻¹(1),6

round(2sin⁻¹(1),6

round(cos⁻¹(-1),6

```

These three statements will print `3.141593`.

---

**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.

# Answer
> 2 votes
# Julia 1.0, 16 bytes

```
show(acos(-1))##

```

Try it online!

This is the default precision printed, I sadly have to add 2 dummy characters but I don't think it's possible to make it shorter

# Answer
> 1 votes
# MY, 7 bytes

```
’2ō"8↑↵

```

Try it online!

## How?

* , decrement the top of the stack (`0` is popped if empty, making the stack `[-1]`). (Same symbol as Jelly)
* `2`, push `2`.
* `ō`, since the top of the stack is two, discard the `2`, pop `n`, then push `acos(n)` (in radians, this gives pi, this symbol is `o` with a negative sign on top of it. `o` (for normal trig) comes from APL).
* `"`, pop the top element of the stack and push it as a string.
* `8`, push `8`.
* , pop `a` then `b`, push `b[:a]` (This is another symbol taken from APL).
* , output with a new line (OUTPUT \<- STACK).

# Answer
> 1 votes
# Haskell, 15 bytes

```
 acos(-1)-3e-15

```

Try it online!

Using @JungHwanMin formula.

# Answer
> 1 votes
# Perl 5, 40 bytes

```
}{$\=$\/~(2*$_)*~$_+2for-130..-2

```

Requires the command line option `-pMbignum`, counted as 8.

**Sample Useage:**

```
$ perl -pMbignum test.pl < /dev/null
3.141592653589793238462643383279502884197

```

I apologize for no TIO link, it doesn't seem to support `bignum` (or an unmatched opening brace...).

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

```
"]a:5;."3no>n<

```

Try it online!

There's a couple of unprintables in there, with the first having value 26 and the second 141.

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

```
i;main(){for(;i<46;)printf(i++?"%02d":"3.",i[L"0;5:a]î.+& O2TÅ©']KiR J^-\N¤>cV0ý*uO"]);}

```

Try it online!

Hardcode 99 bottle of digits

# Answer
> 0 votes
# Pyth, 9 bytes

```
<`.ttZ4 T

```

**Try it here.**

Works with the fact that .

# Answer
> 0 votes
# Ruby, 16 bytes

```
->{Math.acos -1}

```

Try it online!

# Answer
> 0 votes
# Excel VBA, 16 Bytes

Anonymous VBE immediate window functions that takes no input and output to any of Excel VBA's STDOUTs

<sub>*Each line represents a separate function that returns Pi of length 16*</sub>

```
?Mid(4*Atn(1),1)
```

```
?Str([Acos(-1)])
```

```
Debug.?4*Atn(1);
```

```
MsgBox[Acos(-1)]
```

```
[A1]="=ACOS(-1)"
```

# Answer
> 0 votes
# Octave, 16 bytes

```
vpa(acos(-1),16)

```

Try it online!

I'm having a hard time imagining how this could be shorter...

# Answer
> 0 votes
## PHP, 14 Bytes

Try it online!

```
<?=acos(-001);

```

A bit tricky, but the precition of `M_PI` is `3.1415926535898`

# Answer
> 0 votes
# Brainfuck (32 bit), ~~672~~ 660 bytes

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

```

All credit should go to Felix Nawothnig's yapi.b.

Should you decide to downvote, please leave a comment explaining why.

# Answer
> 0 votes
# Perl 6, 16 bytes

```
{4*atan       1}

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 9 bytes

```
»Øȯ\œ»k6/

```

Try it online!

Compressed integer 314159265 divided by 100000000.

## Thunno 2, 4 bytes

```
kP5ɱ

```

Try it online!

Using built-in Pi constant.

---
Tags: code-golf, pi, floating-point, self-referential
---


title: How long is the number in this base?

text:
# Question
Title: How long is the number in this base?
Given a positive integer \\$n\\$ and another positive integer \\$b\\$ (\\$1 \< b \< 36\\$), return the number of digits/length of \\$n\\$ in base \\$b\\$

```
1597 16 -> 3
1709 9 -> 4
190 29 -> 2
873 24 -> 3
1061 27 -> 3
289 26 -> 2
1575 34 -> 3
1135 15 -> 3
1161 22 -> 3
585 23 -> 3
1412 23 -> 3
1268 14 -> 3
714 12 -> 3
700 29 -> 2
1007 35 -> 2
292 17 -> 3
1990 16 -> 3
439 3 -> 6
1212 17 -> 3
683 31 -> 2
535 25 -> 2
1978 32 -> 3
153 8 -> 3
1314 33 -> 3
433 2 -> 9
655 35 -> 2
865 19 -> 3
1947 25 -> 3
1873 32 -> 3
1441 12 -> 3
228 30 -> 2
947 2 -> 10
1026 11 -> 3
1172 24 -> 3
1390 32 -> 3
1495 21 -> 3
1339 10 -> 4
1357 9 -> 4
1320 27 -> 3
602 5 -> 4
1462 16 -> 3
1658 9 -> 4
519 11 -> 3
159 3 -> 5
1152 11 -> 3
1169 33 -> 3
1298 7 -> 4
1686 32 -> 3
1227 25 -> 3
770 15 -> 3
1478 20 -> 3
401 22 -> 2
1097 7 -> 4
1017 9 -> 4
784 23 -> 3
1176 15 -> 3
1521 7 -> 4
1623 23 -> 3
1552 13 -> 3
819 15 -> 3
272 32 -> 2
1546 12 -> 3
1718 4 -> 6
1686 8 -> 4
1128 2 -> 11
1617 34 -> 3
1199 34 -> 3
626 23 -> 3
991 9 -> 4
742 22 -> 3
1227 11 -> 3
1897 12 -> 4
348 35 -> 2
1107 11 -> 3
31 26 -> 2
1153 26 -> 3
432 4 -> 5
758 9 -> 4
277 21 -> 2
472 29 -> 2
1935 21 -> 3
457 27 -> 2
1807 26 -> 3
1924 26 -> 3
23 27 -> 1
558 30 -> 2
203 15 -> 2
1633 8 -> 4
769 21 -> 3
1261 32 -> 3
577 7 -> 4
1440 22 -> 3
1215 35 -> 2
1859 23 -> 3
1702 35 -> 3
1580 12 -> 3
782 15 -> 3
701 32 -> 2
177 24 -> 2
1509 28 -> 3

```

Shortest code in bytes wins.

# Answer
> 8 votes
# JavaScript (V8), 21 bytes

```
b=>g=n=>n&&1+g(n/b|0)

```

Try it online!

# Answer
> 7 votes
# Python 2, 28 bytes

```
f=lambda x,b:x and-~f(x/b,b)

```

Try it online!

thanks @Kevin Cruijssen for -1 byte by using python 2 instead of python 3

# Answer
> 6 votes
# APL (Dyalog Extended), 2 bytes (SBCS)

Anonymous tacit infix function taking \\$b\\$ as left argument and \\$n\\$ as right argument.

```
≢⊤

```

Try it online!

tally the digits of

the anti-base (i.e. the representation in the given base)

Note that this is wasteful in that it actually does the base conversion.

## APL (Dyalog Unicode), 4 bytes

Anonymous tacit infix function taking \\$b\\$ as left argument and \\$n\\$ as right argument.

```
⌊1+⍟

```

Try it online!

floor

`1+` the incremented

log

Implements \\$⌊1+\log\_bn⌋\\$.

# Answer
> 6 votes
# Zsh, 20 bytes

*My first Zsh answer, cobbled together using these very helpful posts.*

```
<<<${#v=$[[##$2]$1]}

```

Try it online or run the test suite.

Full program taking \\$n\\$ and \\$b\\$ as arguments.

### Commented

```
<<<                  # print
   ${#             } # length in characters of
      v=             # set dummy variable v to
        $[[##$2]$1]  # n ($1) in base b ($2)

```

---

Here's an alternative offered by @pxeger. The byte count is the same but the dummy variable is elegantly avoided using parameter expansion.

```
<<<${#:-$[[##$2]$1]}

```

Attempt This Online!

# Answer
> 5 votes
# Pyth, ~~4~~ 3 bytes

```
ljF

```

Try it online!

```
     # implicitly output
l    #   len of
 jF  #     convert first element in input to base second element of input

```

-1 byte thanks to Mr. Xcoder

# Answer
> 4 votes
# Charcoal, 5 bytes

```
ＩＬ↨ＮＮ

```

Try it online! Link is to verbose version of code. Works for any `b>1`. Unfortunately `Base` doesn't accept implicit arguments, so I have to explicitly input the `n` and `b`. Explanation:

```
   Ｎ    Input `n` as an integer
    Ｎ   Input `b` as an integer
  ↨     Convert `n` to base `b` as an array
 Ｌ      Take the length
Ｉ       Cast to string
        Implicitly print

```

# Answer
> 4 votes
# Japt v1.4.5, ~~4~~ 3 bytes

```
slV

```

Try it here

# Answer
> 4 votes
# Retina 0.8.2, 35 bytes

```
\d+
$*
+`\b(1+) (\1)+1*
 $1 $#2$*

```

Try it online! Link includes test cases. Takes input in the order `b`, `n`. Explanation:

```
\d+
$*

```

Convert `b` and `n` to unary.

```
+`\b(1+) (\1)+1*
 $1 $#2$*

```

Repeatedly integer divide `n` by `b` until `n` is less than `b`. With each division, prefix a space to `b`.

```

```

Count the total number of spaces, including the original space. This gives the desired answer.

# Answer
> 4 votes
# Ruby, 21 bytes

```
->n,b{/$/=~n.to_s(b)}

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 2 bytes

```
вg

```

First input is the base \\$b\\$, second input is \\$n\\$.

Try it online or verify all test cases.

Using logarithm like most other answers is **4 bytes**:

```
.n>ï

```

Try it online or verify all test cases.

**Explanation:**

```
      # First (implicit) input-integer = `b`
      # Second (implicit) input-integer = `n`

в     # Convert n to a base-b list
 g    # Pop and get the length of that list
      # (after which the result is output implicitly)

.n    # Log_b(n)
  >   # +1
   ï  # Truncate decimals
      # (after which the result is output implicitly)

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), 13 bytes

```
IntegerLength

```

Try it online!

Of course there's a built-in. Input `[n, b]`.

---

### Wolfram Language (Mathematica), 15 bytes

```
1+⌊Log@##⌋&

```

Try it online!

Not the built-in. Input `[b, n]`.

# Answer
> 3 votes
# Vyxal, 2 bytes

```
τL

```

Try it Online!

Simplest method

`τ` does the base conversion, and `L` gives the length.

# Answer
> 3 votes
# Factor, 16 bytes

```
[ >base length ]

```

Try it online!

It's a quotation (anonymous function) that takes a number and a base (in that order) and returns the length of the number in the given base.

* `>base` Take a number and a base and return the number in the given base as a string.
* `length` The length of the string.

# Answer
> 3 votes
# Jelly, 2 bytes

```
bL

```

Try it online!

Finally, a Jelly answer using ASCII only.

```
bL - Main link. Takes a number on left, base on right
b  - Obtain left base right
 L - Get the length of the string representation of the result

```

# Answer
> 3 votes
# Pascal, 20 characters

Plain translation of the formula: $$ \left\lfloor \frac{\log\_c n}{\log\_c b} + 1\right\rfloor $$

```
trunc(ln(n)/ln(b)+1)

```

# Answer
> 2 votes
# JavaScript (V8), 25 bytes

```
f=(n,b)=>n<b?1:1+f(n/b,b)

```

Try it online!

# JavaScript (V8), 26 bytes, thanks to Adám

```
n=>b=>n.toString(b).length

```

Try it online!

# JavaScript (V8), 32 bytes

```
f=(n,b,x=1)=>b**x<n?f(n,b,x+1):x

```

Try it online!

# Answer
> 2 votes
# , 27 bytes

Or **\>=4.1, 20 bytes** by replacing the word `function` with `\`.

```
function(n,b)log(n,b)%/%1+1

```

Try it online!

# Answer
> 2 votes
# Raku, 21 bytes

This solution works with `n = 0`

```
{$^a.base($^b).chars}

```

```
$^a and $^b are implicit when you call a function with 2 arguments
This is similar to if you call a function with 1 argument
That function will have implicit topic variable $_

```

Try it online!

# Answer
> 2 votes
# TI-Basic, 12 bytes

```
Prompt N,B
1+int(log(N,B

```

Output is stored in `Ans` and is displayed. If not using OS 2.53 MP or higher, `log(N,B` should be replaced with `log(N)/log(B` to add 2 bytes.

# Answer
> 2 votes
# Desmos, ~~23~~ 21 bytes

```
f(n,b)=floor(log_bbn)

```

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# MATL, 3 bytes

```
YAn

```

Try it online!

```
YAn
YA   : dec2base
  n  : numel/size

```

# Answer
> 1 votes
# C (gcc), ~~26~~ 25 bytes

```
f(n,b){n=n?1+f(n/b,b):0;}

```

Try it online!

For input positive integers \\$n\\$ and \\$b\\$ returns the number of digits in \\$n\_b\\$.

# Answer
> 1 votes
# Java, 30 bytes

```
n->b->n.toString(n,b).length()

```

Try it online!

# Answer
> 1 votes
# Rust, 40 bytes

```
|n,b:u8|(n as f64).log(b.into())as u64+1

```

Try it online!

Unfortunately the typecasts are neccessary because the `int_log` feature is not yet stabilized. With the feature the code could be shortened to

```
|n:u64,b|n.log(b)+1

```

# Answer
> 1 votes
## dc, ~~23~~ ~~20~~ 17 bytes

```
[lb/dd0<g]dsgxz1-

```

Takes input with the base in register `b` and the number at the top of the stack. The answer is at the top of the stack once the program completes.

~~Basically, it recursively calculates the number of digits, storing the current count as the second-topmost value in the stack and the current number at the top of the stack.~~

What I did before was pretty long, and it turns out it's shorter to just add new elements when you delete each digit of n in base b, and use the stack's size instead of a register.

Run from the command-line as follows:

```
dc -e '{BASE}sb{NUMBER} [lb/dd0<g]dsgxz1- p'

```

where `{BASE}` should be replaced by the base and `{NUMBER}` should be replaced by the number. Pretty self-explanatory.

### Explanation

```
[lb/dd0<g]dsgxz1-
[        ]dsgx        # Store the text inside the [] in register g and run it
 lb/                  # Divide the current number by the base (in register b)
    dd                # Duplicate it twice, once to store the number of digits,
                      # and another for the comparison with 0
      0<g             # Run the string (function) again if it's more than zero
              z1-     # Find the size of the stack and subtract one

```

The `1-` at the end seems wasteful, but I don't know of a way to reduce it.

PS: This is my first dc program, so any feedback would be appreciated. Also, I'm not sure if this is the best site for dc, would the esolangs one be better? It has less information and wasn't as helpful for me though.

# Answer
> 1 votes
# ErrLess, 27 bytes

```
0m:1$@;<2+]{@;/$;$!0"+0}!.M

```

## Explanation

Basically copied this JS answer.

A macro.

Note: ErrLess doesn't support floating point numbers, so all division is integer division.

```
0m {...} M { Define a macro identified by 0 }

:            { Wrap input in a stack: ((b n)) }
1$           { Add one to the stack, before input, used later: (1 (b n)) }
@;<          { b < n? }
2+]{ {...} } { If not so, }
 @;/          { (1 (b n) b/n) }
 $;$!         { (1 b/n b) }
 0"           { Recurse (yes, I'm using `"` to call the macro...) }
 +            { Add result to the previously added one }
 0            { Add dummy value to stack }
!            { Pop top value of stack, either dummy value or unused arguments, depending on if above code executed }
.            { Halt (return), basically returns either 1 or 1+recurse(b/n, n) }

```

Try it online!

# Answer
> 1 votes
# Excel, 17 bytes

```
=LEN(BASE(A1,B1))

```

Link to Spreadsheet

Counting digits in base conversion beats using log by 1 byte

### Log Method, 18 bytes

```
=INT(LOG(A1,B1))+1

```

# Answer
> 1 votes
# PHP, 22 bytes

```
fn($i)=>1+log(...$i)|0

```

Try it online!

Or the super boring version :

### PHP, 41 bytes

```
fn($n,$b)=>strlen(base_convert($n,10,$b))

```

Try it online!

# Answer
> 1 votes
# PowerShell Core, 42 bytes

```
param($a,$b)for(;$a-gt$b;$i++){$a/=$b}$i+1

```

Try it online!

# Answer
> 1 votes
# Go, 65 bytes, using `math`

```
import."math"
func f(n,b float64)int{return int(Log(n)/Log(b)+1)}

```

Attempt This Online!

# Go, 69 bytes, using `strconv`

```
import."strconv"
func f(n int64,b int)int{return len(FormatInt(n,b))}

```

Attempt This Online!

~~nice~~ wow builtins

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

```
{#y\x}

```

Try it online!

Simple. Convert function argument `x` into base `y` with `\`, then get the length with `#`.

# Answer
> 0 votes
# Core Maude, 107 bytes

```
mod B is pr NAT . op f : Nat Nat -> Nat . vars N B : NzNat . eq f(N,B)= s f(N
quo B,B). eq f(0,B)= 0 . endm

```

The answer is obtained by reducing the `f` function with \\$n\\$ and \\$b\\$.

### Example Session

```
             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
           Thu Nov  4 21:22:07 2021
Maude> mod B is pr NAT . op f : Nat Nat -> Nat . vars N B : NzNat . eq f(N,B)= s f(N
> quo B,B). eq f(0,B)= 0 . endm
Maude> red f(1597, 16) .  --- Expected: 3
result NzNat: 3
Maude> red f(1709, 9) .  --- Expected: 4
result NzNat: 4
Maude> red f(190, 29) .  --- Expected: 2
result NzNat: 2
Maude> red f(873, 24) .  --- Expected: 3
result NzNat: 3
Maude> red f(1061, 27) .  --- Expected: 3
result NzNat: 3
Maude> red f(289, 26) .  --- Expected: 2
result NzNat: 2
Maude> red f(1575, 34) .  --- Expected: 3
result NzNat: 3
Maude> red f(1135, 15) .  --- Expected: 3
result NzNat: 3
Maude> red f(1161, 22) .  --- Expected: 3
result NzNat: 3
Maude> red f(585, 23) .  --- Expected: 3
result NzNat: 3
Maude> red f(1412, 23) .  --- Expected: 3
result NzNat: 3
Maude> red f(1268, 14) .  --- Expected: 3
result NzNat: 3
Maude> red f(714, 12) .  --- Expected: 3
result NzNat: 3
Maude> red f(700, 29) .  --- Expected: 2
result NzNat: 2
Maude> red f(1007, 35) .  --- Expected: 2
result NzNat: 2
Maude> red f(292, 17) .  --- Expected: 3
result NzNat: 3
Maude> red f(1990, 16) .  --- Expected: 3
result NzNat: 3
Maude> red f(439, 3) .  --- Expected: 6
result NzNat: 6
Maude> red f(1212, 17) .  --- Expected: 3
result NzNat: 3
Maude> red f(683, 31) .  --- Expected: 2
result NzNat: 2
Maude> red f(535, 25) .  --- Expected: 2
result NzNat: 2
Maude> red f(1978, 32) .  --- Expected: 3
result NzNat: 3
Maude> red f(153, 8) .  --- Expected: 3
result NzNat: 3
Maude> red f(1314, 33) .  --- Expected: 3
result NzNat: 3
Maude> red f(433, 2) .  --- Expected: 9
result NzNat: 9
Maude> red f(655, 35) .  --- Expected: 2
result NzNat: 2
Maude> red f(865, 19) .  --- Expected: 3
result NzNat: 3
Maude> red f(1947, 25) .  --- Expected: 3
result NzNat: 3
Maude> red f(1873, 32) .  --- Expected: 3
result NzNat: 3
Maude> red f(1441, 12) .  --- Expected: 3
result NzNat: 3
Maude> red f(228, 30) .  --- Expected: 2
result NzNat: 2
Maude> red f(947, 2) .  --- Expected: 10
result NzNat: 10
Maude> red f(1026, 11) .  --- Expected: 3
result NzNat: 3
Maude> red f(1172, 24) .  --- Expected: 3
result NzNat: 3
Maude> red f(1390, 32) .  --- Expected: 3
result NzNat: 3
Maude> red f(1495, 21) .  --- Expected: 3
result NzNat: 3
Maude> red f(1339, 10) .  --- Expected: 4
result NzNat: 4
Maude> red f(1357, 9) .  --- Expected: 4
result NzNat: 4
Maude> red f(1320, 27) .  --- Expected: 3
result NzNat: 3
Maude> red f(602, 5) .  --- Expected: 4
result NzNat: 4
Maude> red f(1462, 16) .  --- Expected: 3
result NzNat: 3
Maude> red f(1658, 9) .  --- Expected: 4
result NzNat: 4
Maude> red f(519, 11) .  --- Expected: 3
result NzNat: 3
Maude> red f(159, 3) .  --- Expected: 5
result NzNat: 5
Maude> red f(1152, 11) .  --- Expected: 3
result NzNat: 3
Maude> red f(1169, 33) .  --- Expected: 3
result NzNat: 3
Maude> red f(1298, 7) .  --- Expected: 4
result NzNat: 4
Maude> red f(1686, 32) .  --- Expected: 3
result NzNat: 3
Maude> red f(1227, 25) .  --- Expected: 3
result NzNat: 3
Maude> red f(770, 15) .  --- Expected: 3
result NzNat: 3
Maude> red f(1478, 20) .  --- Expected: 3
result NzNat: 3
Maude> red f(401, 22) .  --- Expected: 2
result NzNat: 2
Maude> red f(1097, 7) .  --- Expected: 4
result NzNat: 4
Maude> red f(1017, 9) .  --- Expected: 4
result NzNat: 4
Maude> red f(784, 23) .  --- Expected: 3
result NzNat: 3
Maude> red f(1176, 15) .  --- Expected: 3
result NzNat: 3
Maude> red f(1521, 7) .  --- Expected: 4
result NzNat: 4
Maude> red f(1623, 23) .  --- Expected: 3
result NzNat: 3
Maude> red f(1552, 13) .  --- Expected: 3
result NzNat: 3
Maude> red f(819, 15) .  --- Expected: 3
result NzNat: 3
Maude> red f(272, 32) .  --- Expected: 2
result NzNat: 2
Maude> red f(1546, 12) .  --- Expected: 3
result NzNat: 3
Maude> red f(1718, 4) .  --- Expected: 6
result NzNat: 6
Maude> red f(1686, 8) .  --- Expected: 4
result NzNat: 4
Maude> red f(1128, 2) .  --- Expected: 11
result NzNat: 11
Maude> red f(1617, 34) .  --- Expected: 3
result NzNat: 3
Maude> red f(1199, 34) .  --- Expected: 3
result NzNat: 3
Maude> red f(626, 23) .  --- Expected: 3
result NzNat: 3
Maude> red f(991, 9) .  --- Expected: 4
result NzNat: 4
Maude> red f(742, 22) .  --- Expected: 3
result NzNat: 3
Maude> red f(1227, 11) .  --- Expected: 3
result NzNat: 3
Maude> red f(1897, 12) .  --- Expected: 4
result NzNat: 4
Maude> red f(348, 35) .  --- Expected: 2
result NzNat: 2
Maude> red f(1107, 11) .  --- Expected: 3
result NzNat: 3
Maude> red f(31, 26) .  --- Expected: 2
result NzNat: 2
Maude> red f(1153, 26) .  --- Expected: 3
result NzNat: 3
Maude> red f(432, 4) .  --- Expected: 5
result NzNat: 5
Maude> red f(758, 9) .  --- Expected: 4
result NzNat: 4
Maude> red f(277, 21) .  --- Expected: 2
result NzNat: 2
Maude> red f(472, 29) .  --- Expected: 2
result NzNat: 2
Maude> red f(1935, 21) .  --- Expected: 3
result NzNat: 3
Maude> red f(457, 27) .  --- Expected: 2
result NzNat: 2
Maude> red f(1807, 26) .  --- Expected: 3
result NzNat: 3
Maude> red f(1924, 26) .  --- Expected: 3
result NzNat: 3
Maude> red f(23, 27) .  --- Expected: 1
result NzNat: 1
Maude> red f(558, 30) .  --- Expected: 2
result NzNat: 2
Maude> red f(203, 15) .  --- Expected: 2
result NzNat: 2
Maude> red f(1633, 8) .  --- Expected: 4
result NzNat: 4
Maude> red f(769, 21) .  --- Expected: 3
result NzNat: 3
Maude> red f(1261, 32) .  --- Expected: 3
result NzNat: 3
Maude> red f(577, 7) .  --- Expected: 4
result NzNat: 4
Maude> red f(1440, 22) .  --- Expected: 3
result NzNat: 3
Maude> red f(1215, 35) .  --- Expected: 2
result NzNat: 2
Maude> red f(1859, 23) .  --- Expected: 3
result NzNat: 3
Maude> red f(1702, 35) .  --- Expected: 3
result NzNat: 3
Maude> red f(1580, 12) .  --- Expected: 3
result NzNat: 3
Maude> red f(782, 15) .  --- Expected: 3
result NzNat: 3
Maude> red f(701, 32) .  --- Expected: 2
result NzNat: 2
Maude> red f(177, 24) .  --- Expected: 2
result NzNat: 2
Maude> red f(1509, 28) .  --- Expected: 3
result NzNat: 3

```

### Ungolfed

```
mod B is
    pr NAT .
    op f : Nat Nat -> Nat .
    vars N B : NzNat .
    eq f(N, B) = s f(N quo B, B) .
    eq f(0, B) = 0 .
endm

```

Maude *does* have logarithms, but only for floats and only the natural logarithm. To get the number of digits we'd need to compute \\$\mathrm{ceiling}(\log(n) / \log(b))\\$, which actually winds up being a few bytes longer than just doing repeated division.

# Answer
> 0 votes
# Nibbles, 1.5 bytes (3 nibbles)

```
,`@

```

Boring but at least short. Input is base, then integer.

```
,       # length of
`@      # digits in given base

```

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

```
+:to_s|:+@

```

Attempt This Online!

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

```
B

```

Try it online!

Built-in for "convert to base". The `L` flag takes the length.

---
Tags: code-golf, math, base-conversion
---


title: Golf a transcendental number

text:
# Question
Title: Golf a transcendental number
## Definitions

* An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of `2` is algebraic, because it is a zero of `x^2 - 2`.
* A transcendental number is a real number which is not algebraic.

## Task

You are to choose a transcendental number.

Then, write a program/function that takes a positive integer `n` and output the `n`-th **decimal** digit after the decimal point of your chosen transcendental number. You must state clearly in your submission, which transcendental number is used.

You can use 0-indexing or 1-indexing.

## Example

`e^2=7.389056098...` is a transcendental number. For this number:

```
n output
1 3
2 8
3 9
4 0
5 5
6 6
7 0
8 9
9 8
...

```

Note that the initial `7` is ignored.

As I mentioned above, you can choose other transcendental numbers.

## Scoring

This is . Lowest score in bytes wins.

# Answer
> 122 votes
# Python, 3 bytes

```
min

```

Try it online!

Takes a number string, outputs its smallest digit as a smallest character. For example, `254` gives `2`. The decimal with these digits starts

```
0.0123456789011111111101222222220123333333012344444401234555550123456666012345678801234567

```

This is OEIS A054054.

**Claim:** This number `c` is transcendental

**Proof:** Note that `c` is very sparse: almost all of its digits are zero. That's because large `n`, there's high probability `n` has a zero digit, giving a digit min of zero. Moreover, `c` has long runs of consecutive zeroes. We use an existing result that states this means `c` is transcendental.

Following this math.SE question, let `Z(k)` represent the position of the `k`'th nonzero digit of `c`, and let `c_k` be that nonzero digit, a whole number between `1` and `9`. Then, we express the decimal expansion of `c`, but only taking the nonzero digits, as as the sum over `k=1,2,3,...` of `c_k/10^Z(k)`.

We use the result of point 4 of this answer by George Lowther: that `c` is transcendental if there are infinitely many runs of zeroes that are at least a constant fraction of the number of digits so far. Formally, there must be an `ε>0` so that `Z(k+1)/Z(k) > 1+ε` for infinitely many `k`. We'll use `ε=1/9`

For any number of digits `d`, take `k` with `Z(k) = 99...99` with `d` nines. Such a `k` exists because this digit in `c` is a `9`, and so nonzero. Counting up from `99...99`, these numbers all contain a zero digit, so it marks the start of a long run of zeroes in `c`. The next nonzero digit isn't until `Z(k+1) = 1111...11` with `d+1` ones. The ratio `Z(k+1)/Z(k)` slightly exceeds `1+1/9`.

This satisfies the condition for every `d`, implying the result.

# Answer
> 41 votes
# Pyth, 1 byte

```
h

```

Input and output are strings. The function takes the first digit of the index. The resulting transcendental number looks like:

`0.0123456789111111111122222222223 ...`

This is transcendental because it is `1/9` plus a number which has stretches of zeroes of length at least a constant fraction of the number. Based on this math.stackexchange answer, that means that the number is transcendental.

There are stretches of zeroes are from digit `100 ... 000` to `199 ... 999`, so ratio of `Z(k+1)` to `Z(k)` is 2 infinitely often.

Thus, the above number minus `1/9` is transcendental, and so the above number is transcendental.

# Answer
> 16 votes
# Python 2, 19 bytes

```
lambda n:1>>(n&~-n)

```

The **n**th digit is **1** if **n** is a power of **2** and **0** otherwise.

Try it online!

# Answer
> 12 votes
# brainfuck, 2 bytes

```
,.

```

Similarly to some other answers, returns the first decimal digit and ignores the rest.

# Answer
> 6 votes
# Jelly, 3 bytes

```
e!€

```

Uses Liouville's constant.

Try it online!

# Answer
> 5 votes
## Retina, 4 bytes

```
1!`.

```

Returns the first digit of the input number. Because that port was so boring, here are some more ports:

```
O`.
1!`.

```

(8 bytes) Returns the minimum digit of the input number.

```
.+
$*
+`^(11)+$
$#1$*
^1$

```

(25 bytes) Returns 1 if the input number is a power of 2.

```
.+
$*_

$.`
+1`.(\d*)_
$1
1!`.

```

(30 bytes) Champernowne's constant.

# Answer
> 4 votes
# Brachylog 2, 7 bytes

```
⟦₁c;?∋₎

```

Try it online!

Calculates digits of the Champernowne constant (possibly times a power of ten due to indexing issues, which clearly don't matter here). Basically, this just concatenates together integers, and then takes the *nth* digit.

# Answer
> 4 votes
# Python 2, 13 bytes

Input and output are strings.

```
lambda n:n[0]

```

The number's nth digit is the most significant digit of n when it is written in decimal.

# Answer
> 4 votes
# MATL, 7 bytes

```
4YA50<A

```

This uses the first of the two numbers given here divided by 3 (which maintains transcendence):

> 1.100110000000000110011...

Input is 1-based. Try it online! Or see the first 20 decimals.

### Explanation

```
4YA     % Convert to base 4 using chars '0', '1', '2', '3' as digits
50<A    % Are all digits less than '2'? Gives 0 (false) or 1 (true)

```

# Answer
> 3 votes
# Python 2, 43 bytes

Champernowne's constant.

```
lambda n:"".join(`i`for i in range(n+1))[n]

```

# Answer
> 3 votes
# JavaScript, 51 bytes

This function computes `n`th digit of Champernowne's Constant. Add `f=` at the beginning and invoke like `f(arg)`. Note that `n` is 1-indexed.

```
n=>[..."1".repeat(n)].map((c,i)=>c*++i).join``[n-1]

```

## Explanation

This function takes in a single argument `n`. It, then, creates an `n`-characters long String of repetitive 1s. Then, it splits that String into an Array of 1s . After that, it iterates over every element of the Array and multiplies them with their index in the Array incremented by 1. Then, it joins the Array together over `""` (empty String) to form a String. At last, it returns the `n`th element of the obtained String.

**Note:** *The type of the returned value is always String*.

## Test Snippet

```
let f =

n=>[..."1".repeat(n)].map((c,i)=>c*++i).join``[n-1]

i.oninput = e => o.innerHTML = f(parseInt(e.target.value,10));
```

```
<input id=i><pre id=o></pre>
```

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

```
2|⍴

```

Try it online! (the test suite generates a range of numbers from `1` to `10000`, converts them to a string, and then applies the train `2|⍴` on them).

Takes the input number as a string and returns its length mod 2. So `123` =\> `3 mod 2` =\> `1`.

The sequence starts off like so:

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

```

so this can be generalised like so: `9 1s 90 0s 900 1s ...`

Multiplying this number by 9 gives us a Liouville number, which is proven to be transcendental.

# Answer
> 3 votes
# Haskell, ~~25 bytes~~ 17 bytes

```
(!!)$concat$map show[1..]

```

Champernowne's Constant can be 0 or 1 indexed as C10\*.01 is still transcendental.

Edit: as per nimis comment you can use the list monad to reduce this to

```
(!!)$show=<<[1..]

```

# Answer
> 2 votes
# JavaScript, 73 bytes

This is a program which computes the `n`th digit of the Liouville Constant, where `n` is the input number given by invoking the function `g` as `g(arg)` (and `n` is 1-indexed). Note that the newline in the code is necessary.

```
f=n=>n<1?1:n*f(n-1);g=(n,r=0)=>{for(i=0;i<=n;i++)if(f(i)==n)r=1
return r}

```

## Explanation

The program consists of two functions, `f` and `g`. `f` is a recursive factorial-computing function, and `g` is the main function of the program. `g` *assumes* to have a single argument `n`. It defines a default argument `r` with a value of 0. It, then, iterates over all the Integers from 0 to `n`, and, in each iteration, checks whether the function `f` applied over `i` (the current index) equals `n`, i.e. whether `n` is a factorial of `i`. If that happens to be the case, `r`'s value is set to 1. At the end of the function, `r` is returned.

## Snippet for Testing

```
f=n=>n<1?1:n*f(n-1);g=(n,r=0)=>{for(i=0;i<=n;i++)if(f(i)==n)r=1
return r}

i.oninput = e => o.innerHTML = g(parseInt(e.target.value,10))
```

```
<input id=i><pre id=o></pre>
```

**Warning:** *Don't put a very large value in the Snippet's input box! Otherwise, your device may freeze!*

# Answer
> 2 votes
# Jelly, 1 byte

Try it online!

1st digit of quoted 0-indexed input.1

1See isaacg's answer for proof of validity.

# Answer
> 2 votes
# Japt, ~~3~~ ~~1+1= 2~~ 1 byte

Another port of feersum's solution.

Takes input as a string.

```
g

```

Try it online

---

## Explanation

```
   :Implicit input of string U
g  :The first character of the string

```

# Answer
> 1 votes
# Pyth, ~~7~~ ~~5~~ 4 bytes

```
@jkS

```

Try it online!

Uses Champernowne's constant.

Saved ~~2~~ 3 bytes thanks to Leaky Nun.

# Answer
> 1 votes
# Java 8, 18 bytes

Same as Dennis' answer for Python 2, the Fredholm number

```
n->(n&(n-1))>0?0:1

```

# Answer
> 1 votes
# Charcoal, 24 bytes (noncompeting)

```
ＮαＡＩＵＶN⟦ＵＧPi⁺α¹⟧β§β⁺α›α⁰

```

Try it online!

**Note:** As of post time, does not work for `n` where `n` is a positive multiple of 14.

# Explanation

```
Ｎα                             Input number to a
   Ａ                  β        Assign to b
     Ｉ                         Cast
       ＵＶN                    Evaluate variable N
            ⟦ＵＧPi⁺α¹⟧         With arguments GetVariable(Pi) and a+1
                        §β⁺α›α⁰ Print b[a+(a>0)]

```

# Answer
> 1 votes
# 05AB1E, ~~3~~ 1 byte

**EDIT**: Using the proof from the other answers, returns the first digit of input

```
¬

```

1-indexed for π (only up to 100000 digits)

```
žs¤

```

How it works

```
žs  # Implicit input. Gets n digits of pi (including 3 before decimal)
  ¤ # Get last digit

```

Or, if you prefer e (still 1-indexed) (only up to 10000 digits)

```
žt¤

```

Try it online!

# Answer
> 1 votes
# TI-BASIC, 16 bytes

Basically tests if the input `N` (1-indexed) is a triangular number. This is the same as returning the `N`th digit of 0.1010010001…, which is proven to be transcendental. The sequence of digits is OEIS A010054.

```
Input N
int(√(2N
2N=Ans(Ans+1

```

# Answer
> 1 votes
# Duocentehexaquinquagesimal, 1 byte

*Ties isaacg's Pyth answer, Erik the Outgolfer's Jelly answer, Neil A.'s 05AB1E answer, and Shaggy's Japt answer for #1.*

```
.

```

Try it online!

# Answer
> 1 votes
# Pyt, 5 bytes

```
Đř!∈Ɩ

```

Try it online!

Liouville Constant

```
Đ           implicit input (n); duplicate
 ř!         get [1!,2!,...,n!]
   ∈        is n in that list?
    Ɩ       coerce to integer; implicit print

```

# Answer
> 1 votes
# Regex (ECMAScript), 13 bytes

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

```

Try it online!

Takes its input in unary, as a string of `x` characters whose length represents the number. The output is returned as the length of capture group `\2`.

Returns the \\$n\\$th digit of \\$0.00020202220202220202220222220202222202220202220222220...\\$, where the \\$n\\$th digit is \\$2\\$ if \\$n\\$ is a composite number, and \\$0\\$ otherwise.

```
           # tail = N = input number
((xx|)x*)  # \1 = the largest proper divisor of N;
           # \2 = 2 if \1 >= 2, or 0 otherwise;
           # tail -= \1
\1+$       # Assert that \1 divides tail

```

If the return value of `\2` is defined to be \\$0\\$ when it is unset, then this can be reduced to **12 bytes**, with \\$0.00010101110101110101110111110101111101110101110111110...\\$ as the transcendental number:

```
(x?(x)*)\1+$

```

Try it online!

### Regex (ECMAScript), 14 bytes

```
((x*)(?=\2)x)*

```

Try it online!

The output of this one is also returned as the length of capture group `\2`.

Returns the \\$n\\$th digit of \\$0.01001100001111000000001111111100000000000000001...\\$ (with 1-indexing). The \\$n\\$th digit of this transcendental number is the 2nd digit of the binary expansion of \\$n+1\\$, OEIS A079944.

```
                # tail = N = input number
(
    (x*)(?=\2)  # \2 = floor(tail / 2); tail -= \2
    x           # tail -= 1
)*              # Iterate the above as many times as possible

```

# Answer
> 0 votes
# Fourier, 16 bytes

```
I~NL~S10PS~XN/Xo

```

**Try it online!**

As other answers have done, outputs the first digit of the input.

An explanation of the code:

```
N = User Input
S = log(N)
X = 10 ^ S
Print (N/X)

```

# Answer
> 0 votes
# JavaScript (ES6)

Just a few ports of some other solutions

---

## feersum's Python solution, 12 bytes

```
n=>(""+n)[0]

```

```
f=
n=>(""+n)[0]
o.innerText=f(i.value=1)
i.oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```

---

## Dennis' Python solution, 13 bytes

```
n=>1>>(n&--n)

```

```
f=
n=>1>>(n&--n)
o.innerText=f(i.value=1)
i.oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o>
```

---

## xnor's Python solution, 20 bytes

```
n=>Math.min(...""+n)

```

# Answer
> 0 votes
# Brain-Flak, 6 + 3 ( `-c`) = 9 bytes

```
({}<>)

```

Try it online!

1st digit of 0-index string input (hence the `-c` flag).

# Answer
> 0 votes
# C#, 13 bytes

```
n=>(n+"")[0];

```

From feersum's solution. Almost same solution than the js port.

Try it online

# Answer
> 0 votes
# J, 2 Bytes

The same solution everyone else is using:

```
{.

```

Returns the first digit of n. IO is on strings

## Liouville's Constant, 9 Bytes

```
(=<.)!inv

```

Returns `1` if input is the factorial of an integer.

## Pi, 13 Bytes

```
{:":<.@o.10x^

```

The last non-decimal digit of pi times 10^n.

# Answer
> 0 votes
# Jelly, 2 bytes

```
LḂ

```

Try it online!

Take the length of the input number modulo 2. Equivalent to this APL answer.

# Answer
> 0 votes
# Dreaderef, 5 bytes

```
7 3 6

```

Try it online!

Returns the first digit of the input.

# Answer
> 0 votes
# Momema, 5 bytes

```
-9*-9

```

Try it online!

Returns the first digit of the input.

# Answer
> 0 votes
# Shakespeare Programming Language, 76 bytes

```
,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Open mind.Speak thy.

```

Try it online!

# Answer
> 0 votes
# Thunno 2 `M`, 0 bytes

```

```

Try it online! or see the start of the number

Port of xnor's Python answer. The `M` flag takes the minimum of the top of stack.

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