title: Display a number in Toki Pona

text:
# Question
Title: Display a number in Toki Pona
Toki Pona is a constructed language with 137ish words, designed to constrain the speaker to expressing ideas in a simple and straightforward manner, reducing ideas to more essential forms.

Often, people attempt to avoid directly expressing numeric quantities in Toki Pona, opting to express them in more practical terms. if one has a very large amount of money ("mani mute mute"), does it matter if it is $3,532,123 or $3,532,124?

However, Toki Pona does have a basic additive number system, (as well as some others that people have proposed but are not widely used) which is capable of expressing exact quantities.

Toki Pona uses the follow words for numbers:

| word | value |
| --- | --- |
| ala | 0 |
| wan | 1 |
| tu | 2 |
| luka | 5 |
| mute | 20 |
| ale | 100 |

The quantity expressed by a series of these words is the sum of all of their values.

A quantity must be expressed in as few words as possible, with the words ordered from greatest value to least. for instance, simply summing the values of the words, 6 could be expressed "tu tu tu", "luka wan", "wan luka", "wan wan wan wan wan wan", or some other variation. however, a valid program will only generate "luka wan" for 6.

# Challenge

Write a program which takes as input a non-negative integer and outputs this integer expressed in the Toki Pona number system.

Standard rules apply. Spaces are required.

# Examples

| input | output |
| --- | --- |
| 0 | ala |
| 1 | wan |
| 2 | tu |
| 28 | mute luka tu wan |
| 137 | ale mute luka luka luka tu |
| 1000 | ale ale ale ale ale ale ale ale ale ale |

# Answer
> 11 votes
# Python 2, 81 bytes

```
lambda n:n/100*'ale '+n/20%5*'mute '+n/5%4*'luka '+n%5/2*'tu '+n%5%2*'wan'or'ala'

```

Try it online!

The naive approach is surprisingly effective. The overhead of an iterative or recursive method seems too high, though I'd like to be proven wrong.

# Answer
> 8 votes
# Jelly,  ~~41~~  39 bytes

-2 thanks to Unrelated String! (Golfed the method of "coin counting".)

```
;%\:ɗ“dÞ¦£‘Jx$ȯWị“&ḍṘṭ.½6²EmSFʂ5ȥṙẠ»Ḳ¤K

```

**Try it online!**

### How?

```
;%\:ɗ“dÞ¦£‘Jx$ȯWị“...»Ḳ¤K - Link: non-negative integer, n
     “dÞ¦£‘               - [100,20,5,2]
    ɗ                     - last three links as a dyad - f(n, [100,20,5,2]):
;                         -   (n) concatenate ([100,20,5,2]) -> [n,100,20,5,2]
  \                       -   cumulative reduce by:
 %                        -     modulo -> [n, n%100, n%100%20, n%100%20%5, n%100%20%5%2]
   :                      -     integer divide ([100,20,5,2]) -> [n//100, n%100//20, n%100%20//5, n%100%20%5//2, n%100%20%5%2]
           Jx$            - repeat indices - e.g. [0,3,2,2,0] -> [2,2,2,3,3,4,4]
               W          - wrap -> [n]
              ȯ           - logical OR (if n was 0 we now get [0] in place of [])
                 “...»Ḳ¤  - ["ale","mute","luka","tu","wan","ala"]
                ị         - index into (1-indexed and modular)
                        K - join with spaces

```

# Answer
> 6 votes
# Ruby, 92 bytes

```
->n{n<1?"ala":[100,20,5,2,1].map{|i|n-=i*j=n/i;"#{%w{luka wan tu mute ale}[i%12%5]} "*j}*""}

```

Try it online!

Saved some bytes by iterating directly through `100,20,5,2,1` and using the formula `i%12%5` to generate a unique index in the range `0..4`for each in order to lookup the word.

I'm pleasantly surprised that `n-=i*(j=n/i)` works as intended without brackets.

# Ruby, 105 bytes

```
->n{n<1?a=["ala"]:5.times{|i|a=*a,"#{%w{ale mute luka tu wan}[i]} "*j=n/k=[100,20,5,2,1][i];n-=j*k}
a*""}

```

Try it online!

# Answer
> 6 votes
# Vyxal `s`, 38 bytes

```
521f20p₁p(nḋ÷)WṪ«øßṀ∞HĊ∴ǑTṄ‟7«⌈ð+*‛Ż₅⟑

```

Try it Online!

```
                         ‛Ż₅⟑ # Handle the base case 0 -> ala
521f20p₁p                     # Create the list 100,20,5,2,1
         (n  )                # Iterate over, pushing each time
           ḋ÷                 # Divmod ToS (initially input) by current number, and iterate - remainder becomes new ToS
              WṪ              # Wrap, getting all the divisions
                        *     # Dot product with
                «...«⌈ð+      # Words, each with a space appended

```

# Answer
> 6 votes
# Pip, 63 bytes

```
Yay?{x:y//aYy%ab.sRLx}MZ[h20 5 2o]"ale mute luka tu wan"^s"ala"

```

Takes the number as a command-line argument. Try it online!

### Explanation

Yay?

```
; Copy the command-line argument from local variable a into global variable y
Ya
; If y is nonzero (truthy),
y?
  ; Take this function (explained below)
  {x:y//aYy%ab.sRLx}
 ; and map it to pairs of items from
 MZ
  ; this list of numbers
  [100 20 5 2 1]
  ; and this string of words, split on spaces
  "ale mute luka tu wan" ^ s
 ; Else (if y is zero), output ala
 "ala"

```

The mapping function gets a number as its first argument `a` and the corresponding word as its second argument `b`:

```
{
 ; Set x to y (the input number) int-divided by a (the Toki Pona number)
 x: y//a
 ; Update y to be y mod a
 Y y%a
 ; Concatenate b (the Toki Pona word) with space...
 b . s
 ; ... and return a list of x copies of that string
  RL x
}

```

# Answer
> 5 votes
# Retina 0.8.2, 60 bytes

```
.+
$*
1{100}
ale
1{20}
mute
1{5}
luka
11
tu
1
wan
^$
ala

```

Try it online! Link includes test cases. Explanation:

```
.+
$*

```

Convert to unary.

```
1{100}
ale
1{20}
mute
1{5}
luka
11
tu
1
wan

```

Greedily match the appropriate numbers. `wan` doesn't need a space since it can only appear once.

```
^$
ala

```

Fix `0` separately.

# Answer
> 4 votes
# JavaScript (V8), ~~109~~ 96 bytes

```
x=>(g=s=>n=>(s+" ").repeat(x/n,x%=n))`ale`(100)+g`mute`(20)+g`luka`(5)+g`tu`(2)+g`wan`(1)||"ala"

```

Try it online!

# Answer
> 4 votes
# Scratch, 46 blocks

```
set [output v] to [] // setup
set [count v] to [1]
if <(input) = [0]> then
set [output v] to [ala] // 0 in toki pona
else
repeat [5] // every number word
repeat ([floor v] of ((input) / (item (count) of [value v] // repeats every word in order
set [output v] to (join (output) (item (count) of [number v] // the script that generates the number
set [input v] to ((input) - (([floor v] of ((input) / (item (count) of [value v]))) * (item (count) of [value v]) // the script that updates the loop by finding a number
end
change [count v] by [1] // it makes sure that it will move on to the next word

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 90 bytes

```
(n,r,t='0ala1wan2tu5luka20mute100ale'.match(n+'(\\D+)|$')[1])=>t?r?t+' '+f(r):t:f(n-1,-~r)

```

Try it online!

---

# JavaScript (Node.js), 91 bytes

```
n=>'100ale 20mute 5luka 2tu 1wan'.replace(/(\d+)(\D+)/g,(_,a,b)=>b.repeat(n/a,n%=a))||'ala'

```

Try it online!

This solution may introduce a trailing space, while the first one won't.

# Answer
> 3 votes
# Python 3, 143 142 132 bytes

```
def c(s):
 d,x={100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'},''
 if s==0:x+='ala'
 else:
  for i in d:
   x+=s//i*(d[i]+' ')
   s%=i
 print(x)

```

Try it online!

Previous submission:

# Python 3, 143 bytes

```
def c(s):
 if s==0:
  print('ala')
 else:
  d = {100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'}
  for i in d:
   print(s//i*d[i],end=' ')
   s%=i

```

Try it online!

Thank you Jo King for pointing out non inclusion of whitespace
emanresu A, have provided the links now
Thank you Kevin Cruijssen and Jo King♦ for the `if s==0` contraction

**Jo King♦'s solution:**

# Python 3, 116 bytes

```
def c(s,d={100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'},x=''):
 for i in d:x+=s//i*(d[i]+' ');s%=i
 print(x or'ala')

```

Try it online!

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

```
{×⍵:1↓∊(∊(⊂0 2∘⊤)@4⊢0 5 4 5⊤⍵)/' '(=⊂⊢)' ale mute luka tu wan'⋄'ala'}

```

Try it online!

`×⍵` if  is positive:
`' '(=⊂⊢)' ale ...'` split into a list of substrings, where each starts with a space.
`0 5 4 5⊤⍵` Mixed radix decode, this results in a length 4 vector, where the first three are the 100, 20 and 5 places, and the fourth encodes the 1 and 2 places
`∊(⊂0 2∘⊤)@4` split the last into two numbers
`/` repeat each string from the previously generated list this many times
`1↓∊` join into a single string and remove leading space

`⋄'ala'` if the input was 0, return this string

# Answer
> 2 votes
# Python 3, 191 bytes

```
def f(x):
	k=[[]]+[0]*x
	for i in range(1,1+x):
		for j,q in[[1,"wan"],[2,"tu"],[5,"luka"],[20,"mute"],[100,"ale"]]:
			if j<=i:p=k[i-j]+[q];k[i]=min(k[i]or p,p,key=len)
	return k[x]or["ala"]

```

Try it online!

This is definitely not the shortest approach but it works in linear time using dynamic programming which was my intent. Even then, there is almost certainly a shorter linear approach, and more so probably a shorter dynamic programming method anyway.

**Edit**: never mind, I'm pretty sure this solution is straight up constant time. You may as well just go upvote that instead; I haven't golfed in a while and tunneled on the wrong approach.

# Answer
> 2 votes
# Charcoal, 56 bytes

```
Ｎθ¿¬θala«Ｆ⪪”→"jρ§φ|XºM″℅^§¶⬤]r⊗x｜Ｋ” ¿Σι≧÷Ｉιφ«×⁺ι ÷θφ≧﹪φθ

```

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

```
Ｎθ

```

Input `n`.

```
¿¬θala«

```

If `n` is zero then just print `ala`, otherwise:

```
Ｆ⪪”→"jρ§φ|XºM″℅^§¶⬤]r⊗x｜Ｋ”

```

Split the compressed string `10 ale 5 mute 4 luka 2 tu 2 wan` on spaces and loop through the substrings.

```
¿Σι

```

If this substring is numeric, ...

```
≧÷Ｉιφ«

```

... integer divide the predefined variable `1000` by its value, otherwise:

```
×⁺ι ÷θφ

```

Integer divide the input by the predefined variable and print the space-suffixed current string that many times.

```
≧﹪φθ

```

Reduce the input modulo the predefined variable.

# Answer
> 2 votes
# 05AB1E (legacy), 39 bytes

```
т20 5Y)vy‰`}).•Ð‰#¬êAš’ŒÞƒÜ•#ð«*J¨'ãà‚à

```

Try it online or verify all test cases.

Uses the legacy version of 05AB1E (built in Python), because the new version of 05AB1E (built in Elixir) can't take the maximum on strings for \\$n=0\\$. This would be **40 bytes** in the new version with an if/else construction.

**Explanation:**

```
т                  # Push 100
 20                # Push 20
    5              # Push 5
     Y             # Push 2
      )            # Wrap all values into a list: [100,20,5,2]
       v           # Foreach `y` over these values:
        y‰         #  Divmod the (implicit) input or previous value by `y`
          `        #  Pop and push the n//y and n%y separated to the stack
       })          # After the loop: wrap all values on the stack into a list
.•Ð‰#¬êAš’ŒÞƒÜ•    # Push compressed string "ale mute luka tu wan "
               #   # Split it on spaces: ["ale","mute","luka","tu","wan",""]
                ð« # Append a space to each
*                  # Repeat these strings the previous calculated values amount of times
 J                 # Join this list of strings to a single string
  ¨                # Remove the trailing space
   'ãà‚           '# Pair it with dictionary string "ala"
       à           # Pop and push the maximum string of this pair
                   # (after which it is output implicitly as result)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `.•Ð‰#¬êAš’ŒÞƒÜ•` is `"ale mute luka tu wan "` and `'ãà` is `"ala"`.

# Answer
> 2 votes
# MathGolf, ~~44~~ 42 bytes

```
k♀I52ΓÉ‼/%]╖)☺ÿmuteÿluka╢→Γùwan▐ +m*y╡╖) ╙

```

Try it online.

**Explanation:**

```
k             # Push the input-integer
 ♀            # Push 100
  I           # Push 20
   5          # Push 5
    2         # Push 2
     Γ        # Wrap the top four values into a list: [100,20,5,2]
      É       # Foreach over this list, using three characters as inner code-block:
       ‼      #  Apply the following two characters separated to the stack
        /     #   Integer-divide
        %     #   Modulo
       ]      # After the loop, wrap all (five) values on the stack into a list
╖)☺           # Push compressed string "ale"
ÿmute         # Push string "mute"
ÿluka         # Push string "luka"
╢→            # Push compressed string "tu"
     Γ        # Wrap all four values into a list: ["ale","mute","luka","tu"]
      ùwan▐   # Append "wan": ["ale","mute","luka","tu","wan"]
            + # Append a space to each: ["ale ","mute ","luka ","tu ","wan "]
m*            # Repeat each string the values amount of times
  y           # Join this list of strings together
   ╡          # Remove the trailing space
    ╖)        # Push compressed string "ala"
       ╙      # Only leave the maximum of the top two strings on the stack
              # (after which the stack joined together is output implicitly as result)

```

# Answer
> 2 votes
# TI-Basic, ~~163~~ ~~160~~ 152 bytes

```
"ale mutelukatu  wan→Str2
{ᴇ2,20,5,2,1→A
{3,4,4,2,3→B
"ala→Str1
Input N
If N:Then
For(I,1,5
While N≥ʟA(I
N-ʟA(I→N
Str1+" "+sub(Str2,4I-3,ʟB(I→Str1
End
End
sub(Ans,5,length(Ans)-4

```

-3 bytes for not storing the final output to `Str1`.
-8 bytes thanks to MarcMush.

The output is stored in `Ans`.

# Answer
> 2 votes
# jq, ~~78~~ 77 bytes

```
./100%.?*"ale "+./20%5*"mute "+./5%4*"luka "+.%5/2%5*"tu "+.%5%2*"wan"//"ala"

```

Try it online!

A translation of dingledooper's Python approach.

In jq, `/` division is floaty but `%` seems to floor the result: `123.789%100` is `23`. Thus we write something like `.%5/2%5` to get the amount of "tu"s.

Slightly clever: `./100%.` will cause an error when the input is zero, and the `?` catches this and replaces with `null`, to which the `//` alternative-operator then provides `"ala"` as a fallback output. This is actually pretty useful because `""//"ala"` is not `"ala"` (i.e. `""` is not falsey in jq.)

Michael Chatiskatzi saved a byte, by moving `?` around so that I don't need whitespace between `?` and `//`. Thanks!

# Answer
> 2 votes
# C (gcc), ~~118~~ 109 bytes

```
f(i){printf(i?(i-=99)>0?"ale ":(i+=80)>0?"mute ":(i+=15)>0?"luka ":(i+=3)>0?"tu ":"wan ":"ala");--i<1?:f(i);}

```

Try it online!

New best for C.

Thanks for Jo King finding 4 bytes for me.

# Answer
> 1 votes
# Python 3, ~~154~~ 138 bytes

```
def f(n,p={100:'ale',20:'mute',5:'luka',2:'tu',1:'wan'},o=''):
	while n:t=[i for i in p if i<=n][0];n-=t;o+=p[t]+' '
	return o[:-1]or'ala'

```

Try it online!

-16 bytes thanks to Jo King.

---

This is an adaptation of dingledooper's answer for Python 3 and with no space at the end:

# Python 3, 93 bytes

```
lambda n:(n//100*'ale '+n//20%5*'mute '+n//5%4*'luka '+n%5//2*'tu '+n%5%2*'wan ')[:-1]or'ala'

```

Try it online!

# Answer
> 1 votes
# Python 3.8 (pre-release), 125 bytes

```
f=lambda n,b=1,l={1:'wan',2:'tu',5:'luka',20:'mute',100:'ale'}:n and(l[(a:=max(b for b in l if b<=n))]+' '+f(n-a,0))or'ala'*b

```

Try it online!

Definitely not the shortest approach, but is the only recursive Python solution AFAIK.

## Explanation

Takes in `n`, the number to translate, and two other utilities: `b` is used to indicate whether `ala` should be appended: it starts at 1 (if the original n is 0, then output `ala`, but is explicitly passed as 0 to exclude `ala` once `n` hits zero in a recursive call.

An additional dictionary `l` is produced, with the numbers being mapped to the Toki Pona translations. In the body of the function, an `and` expression produces the translation with maxima if `n` is truthy, if n is zero then it jumps to the `or` expression and outputs `ala` or `''` depending on the value of `b`. This ends the recursion.

If n is at least 1, we return the dictionary value with the maximal key below or equal to `n`, add a space, and then recall `f` with a reduced `n` accordingly.

# Answer
> 1 votes
# C (gcc), <sup>~~138~~ \\$\cdots\\$ ~~121~~</sup> 118 bytes

```
i;*v=L"\1\2\5\24d";f(n){n||puts("ala");for(i=4;~i;)n/v[i]?printf("wan \0$tu \0$$luka \0mute \0ale "+6*i),n-=v[i]:i--;}

```

Try it online!

*Saved 4 bytes thanks to ErikF!!!*
*Saved ~~14~~ 17 bytes thanks to AZTECCO!!!*
*Saved 3 bytes thanks to ceilingcat!!!*

# Answer
> 1 votes
# x86-16 machine code, PC DOS, 69 bytes

```
00000000: be1c 01ba 2101 85db 740b 83c2 06ac 983b  ....!...t......;
00000010: d872 f72b d8b4 09cd 2175 f3c3 6414 0502  .|.+....!u..d...
00000020: 0161 6c61 2024 2061 6c65 2024 206d 7574  .ala $ ale $ mut
00000030: 6520 246c 756b 6120 2474 7520 2420 2077  e $luka $tu $  w
00000040: 616e 2024 20                             an $

```

Listing:

```
BE 011C     MOV  SI, OFFSET V   ; quantity values to [SI]
BA 0121     MOV  DX, OFFSET W   ; quantity words to [DX]
85 DB       TEST BX, BX         ; check for zero case
74 0B       JZ   QOUT           ; if zero, display 'ala' and exit
        QNEXT:
83 C2 06    ADD  DX, 6          ; skip to next output string index
AC          LODSB               ; next quantity to check into AL
        QLOOP:
98          CBW                 ; clear AH
3B D8       CMP  BX, AX         ; is input less than this quantity?
72 F7       JB   QNEXT          ; if so, check next lowest
2B D8       SUB  BX, AX         ; otherwise reduce input by quantity
        QOUT:
B4 09       MOV  AH, 9          ; display quantity string
CD 21       INT  21H            ; write to stdout
75 F3       JNZ  QLOOP          ; loop if value has not been reduced to zero
C3          RET                 ; return to caller/DOS

V       DB  100, 20, 5, 2, 1
W       DB  'ala $ ','ale $ ','mute $','luka $','tu $  ','wan $ '

```

Callable function, input value in `BX` output to DOS `STDOUT`.

Maybe not the most elegant or byte efficient way to handle output of the variable-length strings...

Sample output using DEBUG (note input values are in hex):

# Answer
> 1 votes
# Excel, 116 bytes

## Formula, 83 bytes

```
=IF(A1,CONCAT(REPT(C1:C4,MOD(A1,D1:D4)/D2:D5))&IF(MOD(MOD(A1,5),2),"wan",""),"ala")

```

## C1:D5, 33 bytes

```
C1: "ale "  D1: =9^9
C2: "mute " D2: 100
C3: "luka " D3: 20
C4: "tu "   D4: 5
            D5: 2

```

Link to Spreadsheet

# Answer
> 1 votes
# Python 3, 117 bytes

```
lambda x:S(S(S(S(S(x*Q,Q*100,"ale "),Q*20,"mute "),Q*5,"luka "),Q*2,"tu ",),Q,"wan ")[:-1]or"ala"
S,Q=str.replace,"q"

```

Try it online!

An obvious find and replace one. Confuses the syntax highlighter - `something or"string"` should be parsed the same as `something or "string"`, not `something o r"string"`.

# Answer
> 1 votes
# Scala, 303 bytes

Try it online!

```
def f(_n:Int)={
    var n=_n
    if(n<1)List("ala")else{
        var a=List[String]()
        List(100,20,5,2,1).zipWithIndex.foreach{case(k,i)=>
            val j=n/k
            a++=(s"${List("ale","mute","luka","tu","wan")(i)} "*j).split(" ")
            n -= j*k
        }
        a.mkString
    }
}

```

Ungolfed version

```
object Main extends App {
  def f(_n: Int): String = {
    var n=_n
    if (n < 1) {
      val a = List("ala")
      a.mkString("")
    } else {
      var a = List[String]()
      val denominations = List(100, 20, 5, 2, 1)
      for ((k, i) <- denominations.zipWithIndex) {
        val j = n / k
        val word = List("ale", "mute", "luka", "tu", "wan")(i)
        val repeatedWord = s"$word " * j
        a ++= repeatedWord.split(" ")
        n -= j * k
      }
      a.mkString("")
    }
  }

  for (x <- 0 to 200) {
    println(s"[$x, ${f(x)}]")
  }
}

```

# Answer
> 0 votes
# PHP, 134 bytes

```
fn($x)=>$x?($g=fn($s,$n,&$y)=>str_repeat("$s ",$y/$n+0*$y%=$n))(ale,100,$x).$g(mute,20,$x).$g(luka,5,$x).$g(tu,2,$x).$g(wan,1,$x):ala;

```

Try it online!

This is the best I could do so far.. too bad `$x` has to be passed explicitly for a PHP arrow function to be able to modify it by reference..

# Answer
> 0 votes
# Perl 5, 85 bytes

```
$_="@{[map{$c=$F[0]/$_;$F[0]%=$_;(/\D+/g)x$c}qw(100ale 20mute 5luka 2tu 1wan)]}"||ala

```

Try it online!

# Answer
> 0 votes
# Haskell, 111 bytes

```
t@((x,w):y)#n|n>=x=w++' ':t#(n-x)|1<2=y#n
_#n=""
f 0="ala"
f n=zip[100,20,5,2,1](words"ale mute luka tu wan")#n

```

Try it online!

# Answer
> 0 votes
# PHP, ~~108~~ 104 bytes

```
foreach([100=>ale,20=>mute,5=>luka,2=>tu,1=>wan]as$v=>$w)for(;$argn>=$v;$argn-=$v)$o.="$w ";echo$o?:ala;

```

Try it online!

I'm so super rusty at PHP on CG, but here it is just for fun... more or less a port of my other answer.

Iterates through the each word's value and reduces the input number by that amount. Keeps reducing as long as the result is positive, each time adding the word to the output. Nothing fancy here, just the only operation used is subtraction.

# Answer
> 0 votes
# Raku, 76 bytes

```
->\n {~flat(<ale mute luka tu wan>Zxx(n/100,n/20%5,n/5%4,n%5/2,n%2))||"ala"}

```

Try it online!

---
Tags: code-golf, natural-language, integer-partitions
---


title: Calculate pi to 5 decimals

text:
# Question
Title: Calculate pi to 5 decimals
This comes from http://programmers.blogoverflow.com/2012/08/20-controversial-programming-opinions/

"Given that Pi can be estimated using the function \\$4 \times (1 - 1/3 + 1/5 - 1/7 + \cdots)\\$ with more terms giving greater accuracy, write a function that calculates Pi to an accuracy of 5 decimal places."

* Note, the estimation must be done by calculating the sequence given above.

# Answer
> 10 votes
## JavaScript, ~~46 58 56~~ 45 bytes

*ES6 update*: Turns out there's more features available to us now that five years have passed.

```
let f=(i=0,a=0)=>i>1e6?a:f(i+4,a+8/-~i/(i+3))

```

This version (**45** bytes; yes, the `let` is required) works in ES6 strict mode *in theory*. In practice, you can run it in V8 (e.g. with node) with `--use-strict --harmony-tailcalls`; the Proper Tailcalls feature isn't widely implemented yet, alas. However, it's specified behaviour, so it should be fine.

If we want to stick to what's widely implemented, and not require strict-mode, we can simply use the ES6 fat-arrow syntax for functions but otherwise retain the same implementation as before (suggested by Brian H) for a cost of **48** bytes.

```
a=>{for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}

```

The choice of name for the single parameter doesn't *really* matter, but we might as well pick one of the names we use so as to minimise the global-scope pollution.

---

```
function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}

```

This version is a function expression; add two characters (e.g. " `f`") if you want it named. This version clobbers the globals `a` and `i`; this could be prevented if we added "`a,i`" to the parameter list.

Makes use of a reformulated version of the algorithm in order to circumvent the need for subtraction.

```
 1/1 - 1/3  +   1/5 - 1/7   +    1/9 - 1/11  + ...
(3/3 - 1/3) + (7/35 - 5/35) + (11/99 - 9/99) + ...
    2/3     +      2/35     +       2/99     + ...
  2/(1*3)   +    2/(5*7)    +     2/(9*11)   + ...

```

Here's a "plain" version without this adjustment:

```
function(){for(a=0,i=1;i<1e6;i+=2)a+=[,4,,-4][i%4]/i;return a}

```

which clocks in at ~~*64*~~ **62** characters.

Thanks to @ardnew for the suggestion to get rid of the `4*` before the `return`.

---

### History

```
function(){for(a=i=0;i<1e6;a+=8/++i/~-(i+=3));return a}     // got rid of `i+=4`; restructured
// Old versions below.
function(){for(a=0,i=1;i<1e6;i+=4)a+=8/i/-~-~i;return a}    // got rid of `4*`
function(){for(a=0,i=1;i<1e6;i+=4)a+=2/i/-~-~i;return 4*a}

```

# Answer
> 8 votes
## Python 59 bytes

```
print reduce(lambda x,p:p/2*x/p+2*10**999,range(6637,1,-2))

```

This prints out 1000 digits; slightly more than the required 5. Instead of using the prescribed iteration, it uses this:

```
pi = 2 + 1/3*(2 + 2/5*(2 + 3/7*(2 + 4/9*(2 + 5/11*(2 + ...)))))

```

The `6637` (the innermost denominator) can be formulated as:

```
digits * 2*log<sub>2</sub>(10)
```

This implies a linear convergence. Each deeper iteration will produce one more binary bit of *pi*.

***If***, however, you insist on using the *tan-1* identity, a similar convergence can be achieved, if you don't mind going about the problem slightly differently. Taking a look at the partial sums:

*4.0, 2.66667, 3.46667, 2.89524, 3.33968, 2.97605, 3.28374, ...*

it is apparent that each term jumps back and forth to either side of the convergence point; the series has alternating convergence. Additionally, each term is closer to the convergence point than the previous term was; it is absolutely monotonic with respect to its convergence point. The combination of these two properties implies that the arithmetic mean of any two neighboring terms is closer to the convergence point than either of the terms themselves. To give you a better idea of what I mean, consider the following image:

The outer series is the original, and the inner series is found by taking the average of each of the neighboring terms. A remarkable difference. But what's truly remarkable, is that this new series also has alternating convergence, and is absolutely monotonic with respect to its convergence point. That means that this process can be applied over and over again, ad nauseum.

Ok. But how?

Some formal definitions. Let *P1(n)* be the *nth* term of the first sequence, *P2(n)* be the *nth* term of the second sequence, and similarly *Pk(n)* the *nth* term of the *kth* sequence as defined above.

*P1 = \[P1(1), P1(2), P1(3), P1(4), P1(5), ...\]*

*P2 = \[(P1(1) +P1(2))/2, (P1(2) +P1(3))/2, (P1(3) +P1(4))/2, (P1(4) +P1(5))/2, ...\]*

*P3 = \[(P1(1) +2P1(2) +P1(3))/4, (P1(2) +2P1(3) +P1(4))/4, (P1(3) +2P1(4) +P1(5))/4, ...\]*

*P4 = \[(P1(1) +3P1(2) +3P1(3) +P1(4))/8, (P1(2) +3P1(3) +3P1(4) +P1(5))/8, ...\]*

Not surprisingly, these coefficients follow exactly the binomial coefficients, and can expressed as a single row of Pascal's Triangle. Since an arbitrary row of Pascal's Triangle is trivial to calculate, an arbitrarily 'deep' series can be found, simply by taking the first *n* partial sums, multiply each by the corresponding term in the *kth* row of Pascal's Triangle, and dividing by *2k-1*.

In this way, full 32-bit floating point precision (~14 decimal places) can be achieved with just 36 iterations, at which point the partial sums haven't even converged on the second decimal place. This is obviously not golfed:

```
# used for pascal's triangle
t = 36; v = 1.0/(1<<t-1); e = 1
# used for the partial sums of pi
p = 4; d = 3; s = -4.0

x = 0
while t:
  t -= 1
  p += s/d; d += 2; s *= -1
  x += p*v
  v = v*t/e; e += 1

print "%.14f"%x

```

If you wanted arbitrary precision, this can be achieved with a little modification. Here once again calculating 1000 digits:

```
# used for pascal's triangle
f = t = 3318; v = 1; e = 1
# used for the partial sums of pi
p = 4096*10**999; d = 3; s = -p

x = 0
while t:
  t -= 1
  p += s/d; d += 2; s *= -1
  x += p*v
  v = v*t/e; e += 1

print x>>f+9

```

The initial value of *p* begins *210* larger, to counteract the integer division effects of *s/d* as *d* becomes larger, causing the last few digits to not converge. Notice here again that `3318` is also:

```
digits * log<sub>2</sub>(10)
```

The same number of iteratations as the first algorithm (halved because *t* decreases by *1* instead of *2* each iteration). Once again, this indicates a linear convergence: one binary bit of *pi* per iteration. In both cases, 3318 iterations are required to calculate 1000 digits of *pi*, as slightly better quota than 1 million iterations to calculate 5.

# Answer
> 5 votes
# Mathematica 42 39 34 33 31 26 32

**Archimedes' Approach** 26 chars

```
N@#*Sin[180 Degree/#]&

```

This reaches the criterion when input is 822.

Question: Does anyone know how he computed the Sin of 180 degrees? I don't.

---

**Leibniz' Approach** (Gregory's series) 32 chars

This is the same function the problem poser gave as an example. It reaches the criterion in approximately one half million iterations.

```
N@4Sum[(-1)^k/(2k+1),{k,0,10^6}]

```

---

**Madhava-Leibniz Approach** 37 chars

This variation uses a few more characters but converges to criterion in only 9 iterations!

```
N@Sqrt@12 Sum[(-1/3)^k/(2k+1),{k,0,9}]

```

# Answer
> 5 votes
## Java (67 chars)

```
float r(){float p=0,s=4,i=1E6f;while(--i>0)p+=(s=-s)/i--;return p;}

```

Note that this avoids loss of significance by adding the numbers up in the correct order.

# Answer
> 4 votes
## Haskell, 32

```
foldr(\k->(4/(2*k+1)-))0[0..8^7]

```

> GHCi\> foldr(\k-\>(4/(2\*k+1)-))0\[0..8^7\]
> 3.141593130426724

Counting a function name it's

## 34

```
π=foldr(\k->(4/(2*k+1)-))0[0..8^7]

```

# Answer
> 4 votes
## APL (14)

```
4×-/÷1-⍨2×⍳1e6

```

# Answer
> 3 votes
**J, 26 chars**

+/+/\_2((4 \_4)&%)\>:+:i.100

Moved from 100 items of sequence to 1e6 items. Also now it's a code tagged and could be copypasted from browser to the console without errors.

```
+/+/_2((4 _4)&%)\>:+:i.1e6

```

# Answer
> 3 votes
## C (GCC) (44 chars)

```
float p(i){return i<1E6?4./++i-p(++i):0;}

```

That's 41 chars, but it also has to be compiled with `-O2` to get the optimiser to eliminate the tail recursion. This also relies on undefined behaviour with respect to the order in which the `++` are executed; thanks to ugoren for pointing this out. I've tested with gcc 4.4.3 under 64-bit Linux .

Note that unless the optimiser also reorders the sum, it will add from the smallest number, so it avoids loss of significance.

Call as `p()`.

# Answer
> 3 votes
## R - 25 chars

```
sum(c(4,-4)/seq(1,1e6,2))

```

# Answer
> 2 votes
# Clojure - 79 chars

```
(fn [](* 4(apply +(map #(*(Math/pow -1 %1)(/ 1.0(+ 1 %1 %1)))(range 377000)))))

```

This creates a function of no arguments which will calculate a float which approximates pi correctly to five decimal places. Note that this does not bind the function to a name such as `pi`, so this code must either be evaluated in place with `eval` as `(<code>)` or bound to a name in which case the solution is

```
(defn p[](* 4(apply +(map #(*(Math/pow -1 %1)(/ 1.0(+ 1 %1 %1)))(range 377000)))))

```

for 82 chars

### About

```
(defn nth-term-of-pi [n] (* (Math/pow -1 n) (/ 1.0 (+ 1 n n))))
(defn pi [c] (* 4 (apply + (map nth-term-of-pi (range c)))))
(def  pi-accuracy-constant (loop [c 1000] (if (< (pi c) 3.14159) (recur (inc c)) c)))
; (pi pi-accuracy-constant) is then the value of pi to the accuracy of five decimal places

```

# Answer
> 2 votes
# Javascript - 33 Characters

```
p=x=>4*(1-(x&2))/x+(x>1?p(x-2):0)

```

Call `p` passing a positive odd number `x` and it will calculate Pi with `(x-1)/2` terms.

# Answer
> 2 votes
## Ruby - 82 chars

```
def f(n,k=n)k>0?(f(n,k-1)+f(n+1,k-1))/2:n<0?0:f(n-1,0)+(-1)**n/(2*n+1.0)end;4*f(9)

```

Try it : https://repl.it/LQ8w

The approach uses the given series indirectly using a numerical acceleration approach. The resulting output is

`pi ≈ 3.14159265161`

vs.

`pi = 3.14159265359`

It starts with

```
f(n,0) = 1/1 - 1/3 + 1/5 - ... + ((-1)**n)/(2*n+1)

```

And then, since this is alternating, we can accelerate the convergence using

```
f(n,1) = (f(n,0) + f(n+1,0))/2

```

And it repeatedly applies this:

```
f(n,k) = (f(n,k-1) + f(n+1,k-1))/2

```

And for simplicity, `f(n) = f(n,n)`.

---

## Ruby - 50 chars

If you don't mind running for a really long while, then you could simply use

```
def f(n)n<0?0:f(n-1)+(-1)**n/(2*n+1.0)end;4*f(1e7)

```

or

```
a=0;for k in 0..1e7 do a+=(-1)**k/(2*k+1.0)end;4*a

```

# Answer
> 2 votes
# VBA - 80 105 characters

From the VBE immediate window:

```
s=-1:x=1:i=3:While Left(4*x,7)<>3.14159:x=x+((1/i)*s):s=-s:i=i+2:Wend:Debug.?4*x

```

Using `Left()` instead of `Round()` saves a character but also makes it more accurate to the definition of the challenge. I'm getting my character count from Notepad++. I do see that other systems may count differently.

The algorithm below is easier to read:

```
Sub p
    s=-1:x=1:i=3
    While Left(4*x,7)<>3.14159
        x=x+((1/i)*s)
        s=-s
        i=i+2
    Wend
    Debug.?4*x
    Debug.?"Pi to 5 places solved in ";(i-1)/2;" steps."
End Sub

```

*If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out `Option Explicit` if shown at the top. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).*

# Answer
> 1 votes
## Perl - 43 39 chars

not sure the rules on anonymous subroutines, but here's another implementation using @FireFly's series construction

```
sub{$s+=8/((4*$_+2)**2-1)for 0..1e6;$s}

```

```
sub p{$s+=(-1)**$_*4/(2*$_+1)for 0..1e6;$s}

```

# Answer
> 1 votes
## C, 69 chars

```
float p,b;void main(a){b++<9e6?p+=a/b++,main(-a):printf("%f\n",4*p);}

```
* Run with no command line parameters (so `a` is initialized to 1).
* Must be compiled with optimization.
* `void main` is strange and non-standard, but makes things work. Without it, the recursion is implemented as a real call, leading to a stack overflow. An alternative is adding `return`.
* Two characters `4*` can be saved, if running with three command line parameters.

# Answer
> 1 votes
# PHP - 56 55 chars

```
<?for($j=$i=-1;1e6>$j;){$p+=($i=-$i)/($j+=2);}echo$p*4;

```

I don't know that I can get it much smaller without breaking the algorithm rule.

# Answer
> 1 votes
## Python - 56 chars

Meh, My python-fu is not strong enough. I couldn't see any more shortcuts but maybe a more experienced golfer could find something to trim here?

```
t=s=0
k=i=1
while t<1e6:t,s,i,k=t+1,k*4./i+s,i+2,-k

```

# Answer
> 1 votes
## Python (49)

```
print 4*sum((-1)**i/(2*i+1.)for i in range(9**6))

```

```
**3.14159**453527

```

# Answer
> 1 votes
# Befunge, 129 bytes

```
p08p109p^v*86%+55:<$$$<
\$\>:#,_@>+\55+/:#^_"."
v>p"~"/:"~"%08p"~"/00p:2\4%-*"(}"
8^90%"~":+2:+g90*+g80*<
>*:**\/+>"~~"00g:"~"`!|

```

Try it online!

In case anyone is wondering, it's an elephant.

# Answer
> 1 votes
# Husk, 16 bytes

```
*_4ṁ\↑^9 9z*İ_İ1

```

Try it online! using series of only 6561 (9^4) terms (times-out on TIO for longer series).

Output is a rational number expressed as a fraction: TIO header multiplies by 100,000 and rounds to nearest integer.

```
*_4ṁ\↑^9 9z*İ_İ1
*_4                 # multiply by -4:
   ṁ                # sum of series of
    \               # reciprocals of
     ↑^9 9          # first 387420489 (9^9) terms of
          z*        # pairwise products of
            İ_      # powers of -1 (-1,1,-1,1,...) and
              İ1    # odd numbers (1,3,5,7,9,...)

```

# Answer
> 1 votes
# jq, 34 characters

```
[range(1;1e6;4)|1/.-1/(.+2)]|add*4

```

Sample run:

```
bash-5.2$ jq -n '[range(1;1e6;4)|1/.-1/(.+2)]|add*4'
3.1415906535898936

```

Try it online!

# Answer
> 0 votes
## Java - 92 84 chars

I cannot beat by far Peter Taylor's result, but here is mine:

```
double d(){float n=0,k=0,x;while(n<9E5){x=1/(1+2*n++);k+=(n%2==0)?-x:x;}return 4*k;}

```

Ungolfed version:

```
double d() {
    float n = 0, k = 0, x;
    while (n < 9E5) {
        x = 1 / (1 + 2 * n++);
        k += (n % 2 == 0) ? -x : x;
    }
    return 4 * k;
}

```

Edit: Saved a few characters using ternary operator.

# Answer
> 0 votes
**Ruby - 54 chars**

```
def a()p=0;1000000.times{|i|p+=8/(4*i*(4*i+2))};p;end;

```

My first try on console

```
def a()i=1;p=0;while i<2**100 do p+=8/(i*(i+2));i+=4;end;p;end;

```

63 chars.

# Answer
> 0 votes
# k (25 chars)

~~4\*+/%(i#1 -1)*'1+2*!i:1000000~~

Slightly shorter:

```
+/(i#4 -4)%1+2*!i:1000000

```

# Answer
> 0 votes
## Perl (76 chars)

```
$y=1e4;for$x(0..1e4-1){$y--while sqrt($x**2+$y**2)>1e4;$a+=$y}print 4*$a/1e8

```

(Result: 3.14159052)

Not the shortest possible solution, but maybe interesting. It's a geometrical one. I calculate the area under a circle.

I got another funny approach, but it's really slow. It counts the number of discrete points in a square that are below a quarter circle and calculates pi from it:

```
$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2

```

It expects the number of iterations as command line argument. Here you can see how run time relates to accuracy. ;)

```
$ time perl -e '$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2' 100
3.1796
real    0m0.011s
user    0m0.005s
sys 0m0.003s

$ time perl -e '$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2' 1000
3.14552
real    0m0.354s
user    0m0.340s
sys 0m0.004s

$ time perl -e '$i=shift;for$x(0..$i){for$y(0..$i){$h++if sqrt($x**2+$y**2)<$i}}print$h*4/$i**2' 10000
3.14199016
real    0m34.941s
user    0m33.757s
sys 0m0.097s

```

# Answer
> 0 votes
# CJam - 21

```
1e6{WI#4d*I2*)/}fI]:+

```

Pretty straightforward calculation of the given series.
CJam is http://sf.net/p/cjam

# Answer
> 0 votes
# Julia - 30 characters

```
sum(4./[1:4:1e6] - 4./[3:4:1e6])

```

# Answer
> 0 votes
# SQL, 253 bytes

```
DECLARE @B int=3, @A varchar(max), @C varchar(max)='1'
WHILE @B<100000
BEGIN
SELECT @C=@C+(select case when (@B-1)%4=0 then'+'else'-'end)+
(SELECT cast(cast(1.0/@B as decimal(9,8)) as varchar(max)))
SELECT @B=@B+2
END
EXECUTE('SELECT 4*('+@C+')')

```

I would provide a SQL Fiddle, but this goes too many loops deep finding the 1/3 1/5 1/7 etc. fractions and gives errors lol. However, if you change `@B<100000` to `1000` then it runs (obviously not to the same number of digits of accuracy).

# Answer
> 0 votes
# GolfScript, 25 bytes

```
7.?,{2*)2.-1??./\/\-}*)4*

```

Try it online!

```
7.?                         # Push 7^7=823543, we just need an odd number bigger than 136120
   ,{               }*      # For every number k from 1 to 823542
     2*)                    # 2*k+1
        2.-1??./            # sqrt(2)/sqrt(2)=1.0 this number is just 1, but it is a float
                \/          # 1.0 / (2*k+1)
                  \-        # Subtract the sequence from this number
                      )     # Add 1 because 1/1 was skipped
                       4*   # Multiply by 4

```

Output:

```
3.141593867855424

```

# Answer
> 0 votes
# Desmos, 30 bytes

```
4\sum_{n=0}^{9^6}(-1)^n/(1+2n)

```

Try it on Desmos

Pretty self-explanatory coding of the sequence. An array-based method, while it sounds like it should be more efficient, runs into Desmos' limitations on array length.

# Answer
> 0 votes
# CJam, 20 bytes

```
V4e5{4T2*)d/WT#*+}fT

```

Try it online!

One byte shorter than aditsu's answer. ;)

## Alternate 20-byter

```
4_e5,f{_2*)W@#*d/}:+

```

Try it online!

Does the same thing, but I like this better for some reason.

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


title: Divisible strings

text:
# Question
Title: Divisible strings
# Task

Given a string `s`, output a truthy value if the ASCII code of each letter is divisible by the length of `s`, and a falsey otherwise.

## Input/Output

Input is a nonempty string containing only ASCII `[32-126]`. Output is a standard truthy/falsey value. Note that you can switch the values, for example returning `0`/`False` if divisible and vice versa

## Test cases

```
Input         Output

Hello         False       (72 101 108 108 111), 5
lol           True        (108 111 108), 3
Codegolf      False       (67 111 100 101 103 111 108 102), 8
A             True        (65), 1
nope          False       (110 111 112 101),4
8  8          True        (56 32 32 56), 4

```

# Answer
# MATL, 4 bytes

```
tn\~

```
* For divisible strings the output is a vector containing only `1`s, which is truthy.
* Otherwise the output is a vector containing several `1`s and at least one `0`, which is falsy.

Try it online! Or verify all test cases including truthiness/falsihood test.

### How it works

```
t   % Implicit input. Duplicate
n   % Number of elements
\   % Modulo
~   % Negate. Implicit display

```
> 5 votes

# Answer
# Befunge-98 (FBBI), 31 bytes

Output is via exit code, `1` for truthy, `0` for falsey cases.

```
#v~\1+
v>53p
>:#v_1q
^  >' %#@_

```

Try it online!

---

Code running with inputs `lol` and `ab`:

small numbers represent literal byte values
> 10 votes

# Answer
# 05AB1E, 5 bytes

```
ÇsgÖP

```

Try it online!

**Commented**

```
        # implicit input    "lol"
Ç       # push ASCII value  [108, 111, 108]
 s      # swap (with input) [108, 111, 108], "lol"
  g     # length            [108, 111, 108], 3
   Ö    # is divisible?     [1, 1, 1]
    P   # product           1

```
> 8 votes

# Answer
# Haskell, ~~42~~ 39 bytes

```
(<1).sum.(map=<<flip(mod.fromEnum).length)

```

```
f s=sum[fromEnum c`mod`length s|c<-s]<1

```

3 fewer bytes thanks to ovs and xnor!

Try it online!
> 8 votes

# Answer
# JavaScript, 32 bytes

Ouput is reversed.

```
s=>Buffer(s).some(c=>c%s.length)

```

Try it online!
> 5 votes

# Answer
# Pyth, ~~8~~ 7 bytes

-1 byte thanks to @isaag

```
!%#lQCM

```

Try it online!

```
!%#lQCM
!        - logical negation of
  #      - filtering
     CM  - ascii values of input with
 % lQ    - func(x): return x % len(input)

```
> 5 votes

# Answer
# Rockstar, ~~205~~ ~~192~~ ~~175~~ 162 bytes

Well, this was fun. Rockstar has no way of reading the length of a string directly, can't convert characters to codepoints and has no modulo operator. Surprised it worked out this short!

```
listen to S
cut S
X's0
D's0
while S at X
N's32
while N-127
cast N into C
if C is S at X
let M be N/S
turn down M
let D be+N-S*M

let N be+1

let X be+1

say not D

```

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

# Answer
# PHP, ~~56~~ 52 bytes

```
for(;$c=ord($argn[$i++]);$c%strlen($argn)?die(f):1);

```

Try it online!

Output is reversed

Execution stops with `f` if any char is not divisible, or empty string (falsy in PHP) if all are divisible

EDIT: saved 4 bytes thanks to @640KB
> 4 votes

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

```
lambda s:all(ord(i)%len(s)<1for i in s)

```

Try it online!

-2 bytes thanks to @ovs
> 3 votes

# Answer
# Wolfram Language (Mathematica), 40 bytes

```
{0}==##&@@ToCharacterCode@#~Mod~Tr[1^#]&

```

Try it online!

thanks to @att for saving some bytes
> 3 votes

# Answer
# K (oK), 11 bytes

```
{~+/(#x)!x}

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~54~~ 53 bytes

```
l;r;f(char*s){l=strlen(s);for(r=0;*s;)r|=*s++%l;l=r;}

```

Try it online!

Returns falsey if the ASCII value of each character is divisible by the length of the input string or truthy otherwise.

### Explanation:

```
l;r;f(char*s){l=strlen(s);for(r=0;*s;)r|=*s++%l;l=r;}
l;r;                                                  // Declare 2 int variables
    f(                                                // Function f taking
      char*s){                                        //   string parameter s
              l=strlen(s);                            // Store length of s in l
                          for(                        // Loop
                              r=0;                    //   initialising r to 0
                                  *s;)                //   until end of s
                                      r|=             // Bitwise or r with
                                         *s           //   the ASCII value of the next
                                                      //   character...
                                           ++         // Aside: push s pointer forward
                                             %l;      //  ... mod the string length
                                                l=r;  // Return r (r will be 0
                                                      //   iff every character was
                                                      //   divisible by the length of the
                                                      //   input string)

```
> 3 votes

# Answer
# Rust, 36 bytes

```
|s|s.iter().all(|x|1>x%s.len()as u8)

```

Try it online!

Takes the input as a `&[u8]`, outputs a `bool`.
> 3 votes

# Answer
# Ruby, ~~43~~ ~~37~~ ~~36~~ 32 bytes

```
->a{a.bytes.all?{|n|n%a.size<1}}

```

if only map could be used on strings..

-10 bytes from ovs.

-1 byte from Dingus.

Try it online!
> 3 votes

# Answer
# Perl 5 `-pF`, 20 bytes

```
$_=!grep ord()%@F,@F

```

Try it online!
> 3 votes

# Answer
# Vyxal, ~~8~~ 5 bytes

```
₌CLœΠ

```

Thanks @Lyxal for saving 3 bytes Try it Online!
> 3 votes

# Answer
# PowerShell Core, ~~40~~ 33 bytes

```
$l=$args.Count
!($args|?{+$_%$l})

```

7 bytes saved thanks to *mazzy*

Try it online!
> 3 votes

# Answer
# Jelly, 4 bytes

```
LḍOP

```

Try it online! or Verify all cases!

**Commmented:** (At least I think it works like this)

```
   P  # product of ...
L     #   does the length
 ḍ    #   ... divide ...
  O   #   the char codes

```
> 2 votes

# Answer
# APL (Dyalog Extended), 7 bytes (SBCS)

Anonymous tacit prefix function

```
⍱≢|⎕UCS

```

Try it online!

are not any of the following true (non-zero)?

the length

`|` divides (lit. division remainder when dividing)

`⎕UCS` the code points
> 2 votes

# Answer
# C# (.NET Core), 25 bytes

```
a=>a.All(x=>x%a.Length<1)

```

Try it online!
> 2 votes

# Answer
# , ~~39~~ 38 bytes

*Edit: -1byte thanks to the new rule that we can output TRUE for FALSE and FALSE for TRUE*

```
function(s)any(utf8ToInt(s)%%nchar(s))

```

Try it online!

Or try the original 39-byte version that outputs TRUE for TRUE...
> 2 votes

# Answer
# Japt `-e`, 6 bytes

```
c vNÎÊ

```

Try it
> 2 votes

# Answer
# MathGolf, 4 bytes

```
$h÷╓

```

Input as a list of characters.

Try it online.

**Explanation:**

```
$     # Get the codepoint of each character in the (implicit) input-list
 h    # Push the length of this list (without popping the list itself)
  ÷   # Check for each codepoint if it's divisible by this length
   ╓  # Pop and push the minimum of the list
      # (after which the entire stack joined together is output implicitly as result)

```
> 2 votes

# Answer
# Pip, 12 bytes

```
!$+(A_Ma)%#a

```

Try it online!

## Explanation

```
!$+(A_Ma)%#a a → input
   (A_Ma)    Map a to Unicode/ASCII codepoints
         %#a Modulo the list by it's length
 $+          Sum up the remainders
!            Not(returns 0 for any positive number, 1 for 0)

```
> 2 votes

# Answer
# Python 3, ~~55~~ 52 bytes

```
N=input();print(not sum([ord(i)%len(N) for i in N]))

```

Try it online!
> 2 votes

# Answer
# Zsh, 31 bytes

```
for c (${(s::)1})((r||=#c%$#1))

```

Try it online!

If we accept a "list of characters" as arguments, then we don't have to split the string for **19 bytes**:

```
for c;((r||=#c%$#))

```

Try it online!
> 2 votes

# Answer
# GolfScript, 20 bytes

```
.,0@{(3$%@+\}3$*;!\;

```

Try it online!

This outputs 1 if the string is divisible and 0 if it isn't. Let S be the string and L its length.

```
.,0@                  # The stack from bottom up will be: L  0  S
    {       }3$*      # Execute this block L times
     (                # Separate first char from the string as a number
      3$%             # Previous number mod L
         @+\          # Add result to the acumulator
                ;     # Discard the ""
                 !    # 1 iff the acumulator is 0
                  \;  # Discard L

```
> 2 votes

# Answer
# Charcoal, 8 bytes

```
¬⊙θ﹪℅ιＬθ

```

Try it online! Link is to verbose version of code. Output is a Charcoal boolean, i.e. `-` for true, nothing for false. Explanation:

```
  θ         Input string
 ⊙          Is there a character where
     ι      Current character
    ℅       Ordinal
   ﹪        Modulo (i.e. is not divisible by)
       θ    Input string
      Ｌ     Length
¬           Boolean NOT
            Implicitly print

```

`⬤θ¬﹪℅ιＬθ` also works of course.
> 1 votes

# Answer
# Factor, 62 bytes

```
: f ( s -- ? ) dup length [ mod ] curry [ + ] map-reduce 0 = ;

```

Try it online!
> 1 votes

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

```
(s)=>{var bs = ASCIIEncoding.ASCII.GetBytes(s);return bs.All(b=>b%s.Length==0);};

```

Try it online!

# C# (Visual C# Interactive Compiler), 27 26 bytes

```
s=>s.All(c=>c%s.Length<1);

```

Try it online!
> 1 votes

# Answer
# Aceto, 21 bytes

```
&L
|%o 1
€l|!
rM@dp

```

### Explanation

We `r`ead a string and xplode it, push the stack `l`ength and `M`emorize that.

Then, after setting the exception catch point (`@`), we always `d`uplicate the top stack element, negate (`!`) it, and m`|`rror horizontally if we get a truthy value (string has ended; we popped a 0). Otherwise, we get the `o`rdinal of the character, `L`oad the memorized value and do modulo (`%`). If this is truthy, we m`|`rror again.

Finally, we raise an exception (`&`) to land back in front of the `d`, for our next character.

If we mirrored, then we eventually land on `p`, printing the top-most element of the stack. In one of the two cases of mirroring, we will have pushed a `1` before.

---

I don't see much potential to golf this down further; there's only one space character used, and 3 newlines. Perhaps one or two bytes could be saved by making it a 16x16 in two lines.
> 1 votes

# Answer
# MAWP, ~~34~~ ~~33~~ ~~24~~ 23 bytes

```
`|_=M0=A0/[M%{0:.}?`]1:

```

Try it!

Thanks to @Razetime for saving 9 bytes!

Explanation:

```
`        Remove starting 1 on stack
|        Push input on stack as ASCII codes
_=M      Set variable M to length of stack (length of input)
0=A      Set variable A to 0
0/       Push 0 and cycle stack
[        Start of loop
M%       Modulo by M
{0:.}    If not 0 then print 0 and terminate
?`       If 0 then pop value
]        End of loop
1:       Print 1

```
> 1 votes

# Answer
# Clojure, 41 chars

```
(every? #(= 0 (mod (int %) (count x))) x)

```

Removing spaces after comment **37 chars**

```
(every? #(= 0(mod(int %)(count x)))x)

```
> 1 votes

# Answer
# Brachylog, 8 bytes

```
ạfᵐ∋ᵛ~l?

```

Try it online!

```
ạfᵐ∋ᵛ~l?
ạ        characters to integer
 fᵐ      find all factors
   ∋ᵛ    every list of factors contain …
     ~l? the length of the input

```

Alternative version,

```
⟨ạzl⟩%ᵛ0
⟨fhg⟩    forks! fA & gB ∧ [A, B]h
 ạzl     zip the code blocks with the length;
          [[108, 3], [111, 3], [108, 3]]
     %ᵛ0 every list must be 0 after modulo

```
> 1 votes

# Answer
# NARS2000 (12 characters)

`(∧/0=⍴|⎕ucs)`

Fork `⍴|⎕ucs` finds residue of each ASCII int value when divided by length of string. `∧/0=` checks if all residue are zero.
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~63~~ 49 bytes

```
lambda h:print({0}=={*[ord(i)%len(h)for i in h]})

```

Try it online!

`*` in the `{}` constructs a `set` which I think is more byte-efficient than using `set()`, which I didn't know.

----

# Python 3.8 (pre-release), 42? bytes

```
lambda h:{0}=={*[ord(i)%len(h)for i in h]}

```

I can't get TIO to output the `True` or `False`. This works with IDLE or Jupyter. Try it online.
> 1 votes

# Answer
# PowerShell Core, 30 bytes

```
!(($args|?{(++$l)})|?{+$_%$l})

```

Try it online!
> 1 votes

# Answer
# Java, 41 bytes

```
s->s.chars().allMatch(i->i%s.length()==0)

```

Try it online!
> 1 votes

# Answer
# Husk, 6 bytes

```
Λo¦L¹c

```

Try it online!

### Explanation

```
Λo¦L¹c   translates = Λo¦L⁰c⁰
Λ     ⁰  all of input:
 o   c   charcode
  ¦      divides
   L⁰    length of input

```
> 1 votes

# Answer
# APOL, 23 bytes

`!(x(ƒ(i %(↶(∋) l(⋒)))))`

Explanation:

```
!(           Not
  x(         Any list item is true
    ƒ(       List-builder for
      i      Input
      %(     Modulo
        ↶(   ASCII codepoint
          ∋  Loop item
       )
       l(    Length of
         ⋒   Loop iterator (what the loop is looping through)
       )
     )
    )
  )
)

```
> 1 votes

# Answer
# Thunno 2 `B`, 3 bytes

```
lḊp

```

Try it online!

#### Explanation

```
lḊp  # Implicit input
     # Convert to charcodes
l    # Length of input
 Ḋ   # Are they divisible
  p  # Product of the list
     # Implicit output

```
> 1 votes

# Answer
# Vyxal 2.4.1 `K`, 3 bytes

```
LḊΠ

```

Try it Online!

I too can play the K flag game, especially given that I invented it.
> 1 votes

# Answer
# jq, 38 characters

```
length as$a|explode|map(.%$a)|all(.<1)

```

Sample run:

```
bash-5.2$ jq -R 'length as$a|explode|map(.%$a)|all(.<1)' <<< 'Hello'
false

bash-5.2$ jq -R 'length as$a|explode|map(.%$a)|all(.<1)' <<< 'lol'
true

```

Try it online! / Try all test cases online!
> 1 votes

# Answer
# C (clang), ~~149~~ 148 bytes

```
#include<stdio.h>
int main(){char s[100];scanf("%s",s);int j;int k=strlen(s);for(int i=0;i<k;i++){if(s[i]%k>0){printf("0");return 0;}};printf("1");}

```

Try it online!
> 0 votes

# Answer
# Excel, 66 bytes

```
=SUM(MOD(CODE(MID(A1,ROW(OFFSET(A1,0,0,LEN(A1))),1))/LEN(A1),1))=0

```

Input is in the cell `A1`.

`ROW(OFFSET(A1,0,0,LEN(A1)))` gives us an array of values from 1 to the length of the input.
`MID(A1,ROW(~),1)` pulls out each character of the input, one at a time.
`CODE(MID(~)` converts those characters to their decimal ASCII equivalent.
`MOD(CODE(~)/LEN(A1),1)` returns just the decimal portion of those codes divided by the input length.
`SUM(MOD(~))=0` adds up all those decimal portions and returns `TRUE` if there weren't any (SUM=0 means everything divided nicely) and `FALSE` if there were.

---

I thought this would have to be an array formula but it seems to work without that. Color me surprised.
> 0 votes

# Answer
# T-SQL, 65 bytes

Returns 1 for true, 0 for false

```
SELECT-1/~max(ascii(substring(@,number,1))%len(@))FROM spt_values

```

**Try it online**
> 0 votes

# Answer
# Go, 76 bytes

```
func f(a string)int{for _,v:=range a{if int(v)%len(a)>0{return 0}}
return 1}

```

Try it online!
> 0 votes

# Answer
# x86-16 machine code, 10 bytes

```
00000000: 880e 0601 acd4 0ae1 fbc3                 ..........

```

Listing:

```
88 0E 0106      MOV  BYTE PTR[CHR_LOOP+2], CL   ; move len to second byte of AAM opcode
            CHR_LOOP:
AC              LODSB                           ; AL = next char
D4 0A           AAM  CL                         ; ZF = (AL % CL == 0)
E1 FB           LOOPZ CHR_LOOP                  ; loop if CX > 0 AND ZF = 1
C3              RET                             ; return to caller

```

As a callable function. Input: string in `SI`, length in `CX`. Output: `ZF` = `1` if `Truthy`, `ZF` = `0` if `Falsey`.

Output of DOS test program:
> 0 votes

# Answer
# Factor \+ `math.unicode`, 33 bytes

```
[ dup length '[ _ mod 0 = ] ∀ ]

```

Try it online!
> 0 votes

---
Tags: code-golf, string
---


title: Convert a decimal to a fraction

text:
# Question
Title: Convert a decimal to a fraction
Write a program that converts a decimal to a mixed, simplified fraction.

Sample input:

```
5.2

```

Sample output:

```
5 + (1/5)

```

The code with the shortest length in bytes wins.

# Answer
> 4 votes
# Ruby, 43

```
y=gets.to_r;puts"#{y.to_i} + (#{y-y.to_i})"

```

Pretty straightforward.

# Answer
> 2 votes
## python 3, 84

```
from fractions import*
a,b=input().split(".")
print("%s + (%s)"%(a,Fraction("."+b)))

```

# Answer
> 2 votes
# GolfScript, 40

```
'.'/~'+'\.~.@,10\?.@{.@\%.}do;:d/\d/'/'@

```

Requires no line terminator in the input. Can probably be golfed further.

# Answer
> 1 votes
## Golf-Basic 84, 32 characters

Executed from a TI-84 calculator

```
i`A:floor(A)→B:A-B→A:d`Bd`A►Frac

```

# Answer
> 1 votes
# Mathematica 73

No cigar this time. `Numerator`, `Denominator` and `Rationalize` are big words.

```
f@x_:=(Row@{⌊#⌋,"+",Numerator@#~Mod~(d=Denominator@#)/d})&[Rationalize@x]

```

Example

```
f[23.872]

```

# Answer
> 1 votes
## GTB, 28

```
`A:floor(A)→B:A-B→A~B~A►Frac

```

# Answer
> 1 votes
# Perl 6 (53 bytes)

Does the output in right, expected format. Would be way shorter if output in invalid format would be allowed. This gets a number, converts it to rational. `nude` method returns denominator and numerator (there are separate `denominator` and `numerator` methods, but they are crazily long.

`[]` is a reduce operator which takes operator between square brackets, and in this case, I use it to shorten the code (so I wouldn't have to specify both array elements, because they are already in correct order (but if they wouldn't, there are `R` operators (like `R/`, `R%`, `Rdiv`, and `Rmod`) that reverse the order of arguments for operator)). `{}` in double quotes puts the result of code in string (like `#{}` in Ruby).

`my \` is declaration of sigilless variable. In this case it doesn't save characters, but it doesn't waste them either, so why not use it. I could have used `my@`, and it would use identical number of characters.

```
my \n=get.Rat.nude;say "{[div] n} + ({[%] n}/{n[1]})"

```

Sample output (just to show the correct format):

```
~ $ perl6 -e 'my \n=get.Rat.nude;say "{[div] n} + ({[%] n}/{n[1]})"'
42.42
42 + (21/50)

```

If negative number support is needed, this would work (2 bytes more).

```
~ $ perl6 -e 'my \n=get.Rat.nude;say "{[div] n} + ({[mod] n}/{n[1]})"'
-42.42
-42 + (-21/50)

```

# Answer
> 1 votes
# R, several lines

How about the way they tought us at grammar school?

```
f=function(s){
  gcd=function(a,b)if(!b)a else gcd(b,a%%b)
  a=strsplit(s,'\\.')[[1]]
  p=10^nchar(a[2])
  x=strtoi(a[2])
  d=gcd(x,p);
  cat(a[1]," + (",x/d,"/",p/d,")",sep="");
}

```

Vaguely: works for positive decimals with finite decimal fraction.

```
> f("23.872")
23 + (109/125)

```

Input must be a string matching "\[0-9\]+\\.\[0-9\]+" regular expression.

# Answer
> 1 votes
# Haskell

Isn't pretty, but whatever

```
import Data.Ratio
main=let r '%'='/';r c=c in interact$(\(x,y)->show x++" + "++map r(show$approxRational y 1e-9)).properFraction.read

```

# Answer
> 1 votes
# Vyxal, ~~20~~ 19 bytes

```
I₌I-ƒJ`% + (%/%)`$%

```

Try it Online!

It's convoluted because of the handling of the output format

## Explained (old)

```
:I₌₴-ƒ\/j`...`$%,
:I                # int(input)
  ₌₴-             # print(top, end=""), input - int(input) [gets the fractional part]
     ƒ            # Turn the decimal into a simplified fraction
      \/j         # Join that on "/"
         `...`    # The string " + (%)" -> this will be used for formatting the output
              $%, # perform string formatting and output the fraction part

```

# Answer
> 1 votes
# Pyth, 34 bytes

```
phAcQ\.s[" + ("/sHKisHJ*TlH\//JK\)

```

Not that proud of this but that output format was getting to my head

Try it online!

# Answer
> 1 votes
# Vyxal, 34 bitsv2, 4.25 bytes

```
1ḋ\+j

```

Does divmod with 1 and then joins on `+`. Outputs `a+b/c`.

Try it Online!

## If the IO format was a bit looser

### 2 bytes

```
1ḋ

```

Does divmod with 1. Outputs `⟨ a | b/c ⟩`

Try it Online!

# Answer
> 0 votes
# Racket, 134 bytes

```
((λ(f[d(denominator f)][n(numerator f)])(printf"~a + (~a)"(quotient n d)(rationalize(/(modulo n d)d)(/ 1 d))))(inexact->exact(read)))

```

Try it online!

---

## Explanation

Racket natively supports fractions. Fractions are referred to as "exact number" as the values of fraction aren't affected by IEEE floating-point conversion.

Racket also has support for `float`s, similar to what is present in other languages. These floats are called inexact numbers because their accuracy is limited to what can be stored in a certain number of bytes (IEEE standards).

> Read more about Racket Numbers.

Since the user inputs a float with a decimal point, we need to convert the number into a fraction using `inexact->exact`. Once our input is converted, we can extract the denominator and the numerator of the fraction.

```
((λ (frac [den (denominator frac)] [num (numerator frac)])
   ...)
 (inexact->exact (read)))

```

After that, We create a format string that will printed with the following format parameters:

1. The whole part of the fraction.
    1. Calculated by dividing the numerator `num` by the denominator `den`.
2. A simplified version of the remaining fraction.
    1. Modulo the numerator `num` by the denominator `den`.
    2. Create a new fraction with the previous step as the numerator and the denominator as `den`.
    3. Rationalize the new fraction with a tolerance of \\$\frac{1}{\text{den}}\\$.

```
((λ (frac [den (denominator frac)] [num (numerator frac)])
   (printf "~a + (~a)"
           (quotient n d)
           (rationalize (/ (modulo n d) d)
                        (/ 1 d))))
 (inexact->exact (read)))

```

---

*Have a great week further!*

---
Tags: code-golf, rational-numbers
---


title: Create a codeblock tool

text:
# Question
Title: Create a codeblock tool
When using Markup, like on the SE network, an indentation of four spaces before a line of text denotes it as part of a code block, as I hope you know. If you don't, here's an example (with `.` representing a space):

....Code
....More code

results in

```
Code
More code

```

The problem is, when you copy-paste code into an answer, you need to indent each line manually. This is especially difficult when working with ungolfed code, as it's likely already indented and can cause confusion. You can just select your code and hit `Ctrl + K`, it turns out. Hours of my life wasted for no reason aside...

So, your goal is, **given an input, return it with four spaces before each line.** In the spirit of saving time copy-pasting, you are to process the entire input as a single string (so long as your language can parse it). If your language is unable to process a character (such as newlines) in strings, you may assume it is denoted/escaped through some other method supported by the language; however, the output must output each line on its own line (so no passing something like `....foo\n....bar`).

Standard loopholes not allowed. As this is , the shortest answer in bytes wins. Good luck!

# Answer
# , 4 bytes

```
Î4É

```

Try it online!

(Note the trailing space)

V is encoded in Latin1, where this is encoded like so:

```
00000000: ce34 c920                                .4.

```

### Explanation

```
Î            " On every line
 4É<space>   " Prepend 4 spaces

```

---

Here's a solution that is also 4 bytes in UTF-8!

```
VG4>

VG          " Select everything
   >        " Indent
  4         " 4 times (with spaces)

```
> 17 votes

# Answer
# Crayon, 7 bytes

```
`¤q;3xq

```

Try it online!

### Explanation

Crayon is a stack-based language designed for creating ASCII-art. It's still in the early stages of development, but it knows just enough to finish this challenge with a rather low byte count:

```
         Implicit: input string is on the stack
`¤       Push a non-breaking space to the stack.
  q;     Draw this at the cursor (0,0 by default) and pop it.
    3x   Move three more spaces to the right.
      q  Draw the input string here (at 4,0).
         Implicit: output the canvas, trimmed to a rectangle

```

Drawing the non-breaking space is necessary because Crayon automatically trims the output to a rectangle, so without the NBSP it would just print the original input.
> 9 votes

# Answer
## Retina, 8 bytes

```
%`^

```

Try it online!

There are four spaces on the second line. Alternative solutions use either `m`^` or `%1`` or `1%`` on the first line. All of these match the position at the beginning of each line and replace it with four spaces.
> 7 votes

# Answer
# Cheddar, 31 bytes

```
@.lines.map(("    ":+)).asLines

```

Really simply, but I posted because it shows off the new functional operators.

`(" ":+)` is the same as `A -> " " + A`. (i.e. `+` op as a function with `" "` bound to LHS).

I don't think even needs explanation
> 7 votes

# Answer
# Python,  ~~44~~  39 bytes

Crossed out  44  is no longer 44 :)

-5 bytes thanks to ovs (avoid dequeue with a prepend)

```
lambda s:' '*4+s.replace('\n','\n    ')

```

**Try it online!**
> 6 votes

# Answer
# JavaScript, 26 bytes

Thanks @Conor O'Brien for golfing off 8 bytes

```
x=>x.replace(/^/gm,"    ")

```

Replace with a regex with /g replaces all instances. m makes the regex treat each line separately for the start of the string ^.

Try it online!
> 6 votes

# Answer
# Jelly, 8 bytes

```
Ỵṭ€⁶ẋ4¤Y

```

**Try it online!**

### How?

```
Ỵṭ€⁶ẋ4¤Y - Main link: string
Ỵ        - split on newlines
      ¤  - nilad followed by ink(s) as a nilad:
   ⁶     -     a space character
    ẋ4   -     repeated four times
 ṭ€      - tack for €ach
       Y - join with newlines

```

Some other 8 byte variants are:
`Ỵṭ€⁶Yµ4¡` (4 repeats of split on newlines, tack a single space);
`⁶ḤḤ;Ð€ỴY` (doubling twice is like multiplying by 4, `Ð€` maps over the right argument, so we can concatenate instead of tacking);
and other rearrangements thereof.
> 4 votes

# Answer
# Python 2, ~~87~~ 45 bytes

```
print' '*4+'\n    '.join(input().split('\n'))

```

Input is taken as `'Line1\nLine2\nLine3...'` (Quotes necessary)

Thanks to @WheatWizard for giving me an idea that helped me golf 42 bytes.
> 4 votes

# Answer
# Emacs, 5 keychords, 5 bytes

```
C-x h M-4 C-x tab

```

In at least one commonly used encoding for keyboard entry, each of these keychords is a single byte: `18 68 b4 18 09`. Emacs entries tend to be very keychord-heavy, as each printable ASCII character stands for itself except as a subsequent character of a multi-character command (meaning that only keychords can be used to give actual commands).

I'm not sure how this compares to Vim (as opposed to V). But Vim is fairly commonly used on PPCG, and so I thought the other side of the editor wars deserves its time in the spotlight too.

This assumes that I/O is done via the buffer (the equivalent of the normal I/O conventions for vim), or taken from a file and output onto the screen (which comes to the same thing). If you do I/O via the region instead, which is natural for some forms of program, you can remove the leading two characters, for a score of 3 bytes; however, I don't think that complies with PPCG rules.

## Explanation

```
C-x h M-4 C-x tab
C-x h               Specify the entire buffer as the region
      M-4           Give the argument 4 to the next command that runs
          C-x tab   Increase the indentation level of each line by a constant

```

The last builtin used here is, of course, incredibly useful for this challenge; the rest is just structure.
> 4 votes

# Answer
# PowerShell, ~~29~~ 28 Bytes

```
"$args"-split"
"|%{" "*4+$_}

```

-1 Thanks to fergusq, using an actual newline instead of the \`n

takes the `"$args"` input as a string (cast using "s) and `-split`s it on a newline, then loops (`%{}`) through it, appending four spaces (`" "*4`) and the line (`$_`) then outputs it implicitly.
> 3 votes

# Answer
# Pyth, 10 Bytes

```
jm+*4\ d.z

```

Try it!

If input as a list of lines would be allowed, I could do it in 7 bytes:

```
jm+*4\

```

Try that

### longer solutions:

12 Bytes:

```
+*4d:Eb+b*4d

```

12 Bytes:

```
+*4dj+b*4d.z

```

13 Bytes:

```
t:E"^|
"+b*4d

```
> 3 votes

# Answer
# Röda, 21 bytes

```
{(_/"
")|[`    $_
`]}

```

Try it online!

It is an anonymous function. The input is pulled from the stream.

Explanation:

```
{
    (_/"\n") |        /* Splits the input at newlines */
    ["    ".._.."\n"] /* For each line, prints four spaces before the line */
}

```
> 2 votes

# Answer
# Perl 5, 11+1 = 12 bytes

11 bytes of code + `-p` flag.

```
s/^/    /mg

```

Try it online!

For once, explanations will be short: The regex replaces each beginning of line (`^` combined with `/m` modifier) by four spaces - the end.
> 2 votes

# Answer
# sed, 16 10 9 bytes

```
s/^/    /

```

Try it online!

**Edits**

Reduced solution size from 16 to 10 bytes thanks to **Kritixi Lithos**.

-1 byte thanks to **seshoumara**.
> 2 votes

# Answer
# Perl 6, 11 bytes

```
*.indent(4)

```

Try it

## Expanded:

```
*\       # declare a WhateverCode lambda/closure (this is the parameter)
.indent( # call the `indent` method on the argument
  4      # with the number 4
)

```
> 2 votes

# Answer
# Java 7, 58 bytes

```
String c(String s){return"    "+s.replace("\n","\n    ");}

```

**Explanation:**

Try it here.

* Append with four leading spaces
* Replace every new-line for a new-line + four spaces
> 2 votes

# Answer
# Brain-Flak, ~~109~~ 103 bytes

-6 thanks to Wheat Wizard

Includes +1 for `-c`

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

```

Try it online!

```
((()()()()()){})        # Add a newline to the beginning
                        # This is needed to get spaces infront of the first line)
{                       # For every character (call it C)
  (({}<>)               #   Move C to the other stack
  [()()((()()()()){})]  #   Push 8 and subtract 10 (\n) from C
  <(((((({}){}){}))))>) #   Push 4 spaces using the 8 from earlier
  )                     #   Push C - 10
  {(<                   #   If C - 10 != 0...
    {}{}{}{}{}          #     Pop the 4 spaces that we added
  >)}{}                 #   End if
  <>                    #   Switch stacks to get the next character
}                       # End while
<>{({}<>)<>}<>          # Reverse the stack (back to the original order)
{}                      # Pop the newline that we added

```
> 2 votes

# Answer
# J-uby, ~~17~~ 16 Bytes

```
~:gsub&' '*4&/^/

```

### Explanation

```
~:gsub           # :gsub with reversed arguments:
                 # (f)[regex,sub,str] == str.gsub(regex, sub)
      &' '*4     # replace with four spaces
            &/^/ # match the start of each line

```

This directly translates to (in Ruby):

```
->s{s.gsub(/^/,' '*4)}

```
> 2 votes

# Answer
# PHP, 43 Bytes

```
<?="    ".strtr($_GET[0],["\n"=>"\n    "]);

```
> 1 votes

# Answer
# Stacked, 13 bytes

```
'^'4' '*mrepl

```

Try it online!

## Explanation

```
'^'4' '*mrepl      (* input: top of stack *)
        mrepl      perform multiline regex replacements,
'^'                  replacing /^/ with
   4' '*             four spaces

```
> 1 votes

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

Saved 2 bytes thanks to *kalsowerus*

```
¶¡4ú»

```

Try it online!

**Explanation**

```
¶¡        # split input on newline
  4ú      # prepend 4 spaces to each
    »     # join by newline

```
> 1 votes

# Answer
# MATL, 12 bytes

```
10&Yb"4Z"@gh

```

Input is a string with newlines. To enter this, you need to concatenate character 10 between the normal characters to represent newline (square brackets are concatenattion):

```
['Code' 10 'More code']

```

Try it at **MATL online!**

### Explanation

```
10&Yb   % Implicit input. Split at char 10 (newline). Gives cell array of strings
"       % For each
  4Z"   %   Push string of 4 spaces
  @g    %   Push the contents of current cell array, i.e. a string with one of the
        %   original lines
  h     %   Concatenate the two strings horizontally
        % Implicit end. Implicit display

```
> 1 votes

# Answer
# CJam, 11 bytes

*Thanks to @Challenger5 for a correction*

```
qN/{S4*\N}%

```

**Try it online!**

### Explanation

```
q              e#  Read whole input as a string with newlines
 N/            e#  Split at newlines, keeping empty pieces. Gives an array of strings
   {     }%    e#  Map this function over the array of strings
               e#  The current string is automatically pushed
    S4*        e#  Push a string of four spaces
       \       e#  Swap. Moves the original string after the four spaces
        N      e#  Push a newline
               e#  Implicity display stack contents

```
> 1 votes

# Answer
# Octave, 17 bytes

```
@(s)["    "';s']'

```

Try it online!
> 1 votes

# Answer
# C, ~~66~~ 65 bytes

```
p(){printf("    ");}f(char*s){for(p();*s;)putchar(*s++)-10||p();}

```

Try it online!
> 1 votes

# Answer
# Vim, 6 keystrokes

```
<Ctrl-V>G4I <Esc>

```

Assumes that the cursor is on the beginning of the file, as if you opened the file from from the command line via `vim filename`.

```
<Ctrl-V>            " Enter visual block move (enables rectangular selection)
        G           " Move to bottom line (selecting the entire first column)
         4          " Repeat the following action 4 times
          I         " Insert at start of (each selected) line
                    " [input a space]
            <Esc>   " Exit insert mode

```

With a vim configured to use 4 spaces for indentation it would be 2 keystrokes: `>G`.
> 1 votes

# Answer
# PHP, 16

```
echo"    $argn";

```

run with `php -R <code>`. `-R` runs the given code for every input line and `$argn` is fed the current input line. So this simply prints each line with additional four spaces in front of it.
> 1 votes

# Answer
# , 3 bytes (Non-competing)

```
4>G

```

This is answer uses a feature that I have been planning on adding for a while, but just got around to adding today. That makes this answer non-competing and invalid for winning. But it's still cool to show off such a useful/competitive feature!

Try it online!

Explanation:

```
4>   " Add an indent of 4 to...
  G  "   Every line from the current line (0 by default) to the end of the buffer

```
> 1 votes

# Answer
# Japt, 7 6 bytes

*Saved 1 byte thanks to @ETHproductions*

```
miS²²R

```

Try it online!

### Explanation:

```
miS²²R
m       // At each char in the input:
 iS²²   //   Prepend " " repeated 4 times
     R  // Rejoin with newlines

```
> 1 votes

# Answer
# UberGenes, 62 bytes

I had to enter this challenge with UberGenes, as a very similar program (that only inserted one space) was one of the first programs I ever wrote in the language, and it seemed like it would be easy to modify for this purpose.

```
=aA=p9=z4=cI=AC+a1-z1:pz=Ao:CA:Ii  =b5+b5-bA+a1=d3*d7:db=i0

```

How it works:

```
=aA                                                         Set a to 61
                                                            (Begin main loop)
   =p9                                                      Set p to 9
      =z4                                                   z counts spaces
         =cI                                                Set c to 61
                                                            (Jumping to p jumps here)
            =AC                                             Put the space at position 61
                                                              at position a.
               +a1-z1                                       Move a right and decrement z
                     :pz                                    Jump to p if z is nonzero
                                                            (Jumping to d jumps here)
                        =Ao                                 Read a character to position a.
                           :CA                              Jump to position 32+3 if input
                                                              was nonzero.
                              :Ii                           Otherwise, jump to position 61,
                                                              causing the entire string
                                                              that begins there to be
                                                              printed before halting.
                                                            (This is position 32+3=35)
                                   =b5+b5                   Set b to 10 (newline).
                                         -bA                Subtract the input character to
                                                              compare it with newline.
                                            +a1             Move a right.
                                               =d3*d7       Set d to 21
                                                     :db    Jump to d if not newline.
                                                        =i0 Jump back to begin main loop.
(The 3 spaces at the end position a space character at position 61 so that, after =cI,
C refers to the space character--it will also be the first space printed.)

```
> 1 votes

# Answer
# Ruby, ~~22~~ 21 Bytes

1 Byte saved thanks to @manatwork

```
->s{s.gsub /^/,' '*4}

```

Takes `s`, replaces all occurences of `/^/` (start of line) with four spaces.
> 1 votes

# Answer
# Actually, 16 bytes

```
9uc;§s⌠' 4*+⌡M@j

```

Try it online!

Explanation:

```
9uc;§s⌠' 4*+⌡M@j
9uc;              push two newlines
    §s            raw input, split on newlines
      ⌠' 4*+⌡M    for each line:
       ' 4*+        prepend 4 spaces
              @j  join with newlines

```
> 1 votes

# Answer
# Swift, 94 bytes

```
func f(g:String){print(g.components(separatedBy:"\n").map{"    "+$0}.reduce("",{$0+"\n"+$1}))}

```

This is a function, that can be used like this:

```
f(g:"YOUR\nSTRING")

```
> 0 votes

# Answer
# GolfScript, 14 bytes

```
n/{' '4*\+}%n*

```

Try it online!

Note: if trailing newline is disallowed, append `:n;` for 17 bytes.
> 0 votes

# Answer
# brainfuck, 57 bytes

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

```

Online interpreter

You need to use `\n` for newlines, although they get parsed as actual newlines (input field at the bottom).

Set EOF = `\0` (go to Options \> End of input \> char = `\0`).
> 0 votes

# Answer
# Gema, 13 characters

```
/.*/=\     $0

```

Sample run:

```
bash-4.3$ gema '/.*/=\     $0' <<< $'Code\nMore code'
    Code
    More code

```
> 0 votes

# Answer
# jq, 24 characters

(19 characters code + 5 characters command line options)

```
(./"\n")[]|"    "+.

```

Sample run:

```
bash-4.3$ jq -sRr '(./"\n")[]|"    "+.' <<< $'Code\nMore code'
    Code
    More code

```

On-line test

## jq, 13 characters

(8 characters code + 5 characters command line options)

If we can rely on the interpreter's line oriented processing mode.

```
"    "+.

```

bash-4.3$ jq -Rr '" "+.' \<\<\< $'Code\nMore code' Code More code

On-line test
> 0 votes

# Answer
# Common Lisp, ~~65~~ 61 bytes

-4 thanks to Julian

```
(loop for l =(read-line t nil)while l do(format t"~4t~A~%"l))

```

Reads from `*standard-input*` (stdin, by default) and writes four spaces followed by each line to `*standard-output*` (stdout, by default).

### Ungolfed

```
(loop :for l := (read-line t nil) :while l :do (format t"~4t~A~%" l))

```

### Explanation

`(read-line t nil)`

Read a line from `*standard-input*` (shorthanded to `t`), not raising an error on EOF (the EOF return value is optional and defaults to `nil`). The line is returned as a string without the trialing "\n".

`(format t "~4t~A~%" l)`

Prints out formatted text to `*standard-output*` (shorthanded to `t`). "~4t~A~%" is a formatting string. ~4t moves to the fourth column (prints 4 spaces), ~A prints out an argument to format, ~% prints out a newline.

`(loop :for l := ... :while l :do ...)`

Each time through the loop, assign l to the result of reading in a line of text, break the loop if there was no line to read, and print out the line with four spaces prepended.
> 0 votes

# Answer
## C#, ~~46~~ 35 bytes

```
s=>"    "+s.Replace("\n","\n    ");

```
> 0 votes

# Answer
## REXX, 41 bytes

```
do while lines()>0
say '    'linein()
end

```

Reads from stdin, writes to stdout.
> 0 votes

# Answer
# Charcoal, 6 bytes

```
ＰＳＭ⁴←

```

Try it online!

**Note:** There is a space at the end

## Explanation

```
ＰＳ     Print next input as string
   Ｍ⁴←  Move 4 cells left
         (it's a space) Print space

```
> 0 votes

# Answer
# Carrot, 22 bytes, non-competing

Non-competing because of a bug with the website not showing leading whitespace in the output that was fixed recently

```
    #^//^.*/gmS"
    "

```

(note the leading spaces on each of the lines)

Try it online here.

### Explanation

First we are in caret mode, where every character gets pushed to the stack (which is just a string). The four leading spaces on the first line push these spaces to the stack. Then the `#` pushes all of the input to the stack. Now the first line has four leading spaces. And the `^` takes us out of caret mode.

Next comes the `/` operator. The function of each operator depends on the argument it takes. In this case, the operator takes in a regex as its argument. The `/` operator with a regex argument returns the matches of the regex. The regex is `/^.*/gm`, this matches every line in the stack (except for the newlines). Now the stack turns from being a string into an array that contains the matches.

The `S` operator with a string argument joins the elements of the stack array with the argument. So in this case, we are joining the matches with this string, `\n` .

To simplify what was done here, the program prepends 4 spaces to the input and then substitutes newlines with a newline and 4 spaces (I really need to add a substitution operator to Carrot).
> 0 votes

# Answer
## Mathematica, 34 bytes

(Needs version 10.)

```
StringReplace[StartOfLine->"    "]

```

Explanation: A string replacement operator where the start of each line is turned into `" "`.
> 0 votes

# Answer
# Tcl, 40

```
puts [regsub -all ^ [read stdin] "    "]

```

demo — Notes:

* Avoid to press backspace key, it will execute the browser's History back.
* To end the input press `Ctrl+D` after you had input all lines (you may have to press two times has it tends to get absorbed has a browser keybinding). If you paste the on a Windows interpreter, use `Ctrl+Z`+`Enter` to mark end of input.
* Pressing arrow keys will make appear strange chars instead of moving cursor.
* Yes, online interpreters really suck
* The rest of code is only for input and output, does not really process the string
> 0 votes

# Answer
# Tcl, 40

Now as a function:

```
proc p t {regsub -all -line ^ $t "    "}

```

demo

Did not save bytes after all!
> 0 votes

# Answer
# Cubix, 28 bytes

```
v.@>i??soS4.^(s<.....u!-Ns<v

```

Try it online!

Net form:

```
      v . @
      > i ?
      ? s o
S 4 . ^ ( s < . . . . .
u ! - N s < v . . . . .
. . . . . . . . . . . .
      . . .
      . . .
      . . .

```

Explanation coming soon...
> 0 votes

# Answer
# Thunno 2 `N`, 7 bytes

```
¶/ð4×s+

```

Try it online!

#### Explanation

```
¶/ð4×s+  # Implicit input
¶/       # Split on newlines
  ð4×    # Push four spaces
     s+  # Prepend it to each
         # Join on newlines
         # Implicit output

```
> 0 votes

---
Tags: code-golf, string, whitespace
---