title: Is string X a subsequence of string Y?

text:
# Question
Title: Is string X a subsequence of string Y?
Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., `''` and `'anna'` are subsequences of `'banana'`.)

### Input

* X, a possibly-empty case-sensitive alphanumeric string
* Y, a possibly-empty case-sensitive alphanumeric string

### Output

* True or False (or equivalents), correctly indicating whether X is a subsequence of Y.

### I/O examples

```
X      Y        output

''     'z00'    True
'z00'  'z00'    True
'z00'  '00z0'   False
'aa'   'anna'   True
'anna' 'banana' True
'Anna' 'banana' False

```

### Criteria

* The shortest program wins, as determined by the number of bytes of source code.

### Example programs

# Answer
# Perl 5, 17 bytes (+1?), full program

```
s//.*/g;$_=<>=~$_

```

Try it online!

Invoke with the `p` flag to the perl interpreter, as in `perl -pe 's//.*/g;$_=<>=~$_'`. Per the established scoring rules when this challenge was originally posted, this flag costs one extra byte. Under more recent rules, AFAICT, it may be free.

Either way, the input strings should be supplied on separate newline-terminated lines on stdin. Output (to stdout) will be `1` if the first input string is a substring of the second, or nothing at all if it's not.

Note that *both* input lines must have a newline at the end, or the program won't work correctly. Alternatively, you can add the `l` command line flag to the invocation to make perl strip the newlines; depending on the scoring rules in effect, this may or may not cost one extra byte. Note that using this flag will also append a newline to the output.

## Original version (snippet, 18 bytes / chars)

```
$x=~s//.*/g,$y=~$x

```

Input is given in the variables `$x` and `$y`, result is the value of the expression (in scalar context). Note that `$x` is modified in the process. (Yes, I know using `$_` instead of `$x` would let me save four chars, but doing that in a snippet that feels a bit too cheesy for me.)

### How does it work?

The first part, `$x=~s//.*/g`, inserts the string `.*` between each character in `$x`. The second part, `$y=~$x`, treats `$x` as a regexp and matches `$y` against it. In Perl regexps, `.*` matches zero or more arbitrary characters, while all alphanumeric characters conveniently match themselves.
> 19 votes

# Answer
### Ruby, 32 characters

```
s=->x,y{y=~/#{[*x.chars]*".*"}/}

```

This solution returns `nil` if `x` isn't a subsequence of `y` and a number otherwise (i.e. ruby equivalents to `false` and `true`). Examples:

```
p s['','z00']        # => 0   (i.e. true)
p s['z00','z00']     # => 0   (i.e. true)
p s['z00','00z0']    # => nil (i.e. false)
p s['anna','banana'] # => 1   (i.e. true)
p s['Anna','banana'] # => nil (i.e. false)

```
> 9 votes

# Answer
## Haskell, ~~51~~ 37

```
h@(f:l)%(g:m)=f==g&&l%m||h%m;x%y=x<=y

```

Thanks to Hammar for the substantial improvement. It's now an infix function, but there seems to be no reason why it shouldn't.

Demonstration:

```
GHCi> :{
GHCi| zipWith (%) [""   , "z00", "z00" , "anna"  , "Anna"]
GHCi|             ["z00", "z00", "00z0", "banana", "banana"]
GHCi| :}
[True,True,False,True,False]

```
> 8 votes

# Answer
# Python, 45 bytes

```
lambda a,b:{1,l:=iter(b)}>{c in l for c in a}
```

Attempt This Online!

Builds on @qwatry's method used in @xnor's answer: `iter` consumes elements as they are searched for, so `c in l` "uses up" the character if it is found.

Some trickery lets us combine the `all` and the iterator assignment:

* `{c in l for c in a}` is a set comprehension which effectively deduplicates its contents, so it's always one of `{}`, `{False}`, `{True}`, or `{False, True}`
* `1` and `0` are equivalent to `True` and `False`
* The `>` operator tests if `{True, iter(b)}` is a strict superset of the result, which is true only if that result is `{}` or `{True}`, i.e. all the `c in l` expressions were true
* By including `l:=iter(b)` in the set, we can sequence the evaluation order correctly with minimal parentheses by reusing the set's `{}` grouping
* It also lets us use `>` instead of `>=` because the iterator will never be present in the boolean set
* Otherwise, `>=` would be necessary because `{True}` is not a strict superset of `{True}`
> 7 votes

# Answer
## Python (48 chars)

```
import re;s=lambda x,y:re.search('.*'.join(x),y)

```

Same approach as Howard's Ruby answer. Too bad about Python's need to import the regex package and its "verbose" `lambda`. :-)
> 6 votes

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

```
lambda a,b:''in[a:=a[a[:1]==c:]for c in b]

```

Try it online!

**Python 3.8 (pre-release), 48 bytes**

```
lambda a,b,j=0:all((j:=1+b.find(c,j))for c in a)

```

Try it online!

In Python 3.10+, we don't need parens around the walrus expression for 46 bytes.

**Python 2, 48 bytes**

```
lambda a,b:re.search('.*'.join(a),b)>0
import re

```

Try it online!

Copied from this answer of Lynn. The `>0` can be omitted if just truthy/falsey output is OK.

**Python 2, 49 bytes**

```
def f(a,b):l=iter(b);print all(c in l for c in a)

```

Try it online!

A dazzling new method introduced to me by qwatry. The idea is that turning `b` into the iterator `l` will consume values whenever they are read. So, checking `c in l` will consume values left to right until it finds one that equals `c` or it reaches the end.

**Python 2, 50 bytes**

```
f=lambda a,b:b and f(a[a[:1]==b[0]:],b[1:])or''==a

```

Try it online!

**Python 2, 50 bytes**

```
lambda a,b:reduce(lambda s,c:s[c==s[:1]:],b,a)==''

```

Try it online!
> 6 votes

# Answer
## Python, 59 characters

```
def s(x,y):
 for c in y:
  if x:x=x[c==x[0]:]
 return x==""

```

I figured my answer would be better expressed in Python.

Edit: Added r.e.s.'s suggestions.
> 5 votes

# Answer
# Brachylog, 2 bytes

```
⊆ᵈ

```

Try it online!

As with this answer,  is a built-in predicate that declares a relationship between the input and output variables, and  is a meta-predicate that modifies it to declare that same relationship between the first and second elements of the input variable instead (and unify the output variable with the second element but as this is a decision problem that doesn't end up mattering here). `X⊆Y` is an assertion that X is a subsequence of Y, therefore so is `[X,Y]⊆ᵈ`.

This predicate (which of course outputs through success or failure which prints `true.` or `false.` when it's run as a program) takes input as a list of two strings. If input is a bit more flexible...

# Brachylog, 1 byte

Try it online!

Takes string X as the input variable and string Y as the output variable. Outputs through success or failure, as before. If run as a full program, X is supplied as the input and Y is supplied as the first command line argument.
> 5 votes

# Answer
## GolfScript (22 chars)

```
X[0]+Y{1$(@={\}*;}/0=!

```

Assumes that input is taken as two predefined variables `X` and `Y`, although that is rather unusual in GolfScript. Leaves `1` for true or `0` for false on the stack.
> 4 votes

# Answer
## C (52 chars)

```
s(char*x,char*y){return!*x||*y&&s(*x-*y?x:x+1,y+1);}

```

Test cases
> 4 votes

# Answer
# Burlesque (6 chars)

6 chars in Burlesque: `R@\/~[` (assuming x and y are on the stack. See here in action.)
> 4 votes

# Answer
# C, 23:

```
while(*y)*x-*y++?0:x++;

```

result in \*x

http://ideone.com/BpITZ
> 4 votes

# Answer
## PHP, 90 characters

```
<?function s($x,$y){while($a<strlen($y))if($y[$a++]==$x[0])$x=substr($x,1);return $x=="";}

```
> 3 votes

# Answer
# C #, ~~70~~ ~~113~~ ~~107~~ 90 characters

```
static bool S(string x,string y){return y.Any(c=>x==""||(x=x.Remove(0,c==x[0]?1:0))=="");}

```
> 3 votes

# Answer
### Scala 106:

```
def m(a:String,b:String):Boolean=(a.size==0)||((b.size!=0)&&((a(0)==b(0)&&m(a.tail,b.tail))||m(a,b.tail)))

```
> 3 votes

# Answer
## CoffeeScript ~~112~~ ~~100~~ ~~95~~ 89

My first attempt at code golf... hope I don't shame my family!

```
z=(x,y)->a=x.length;return 1if!a;b=y.indexOf x[0];return 0if!++b;z x[1..a],y[b..y.length]

```

**Edit**: turns out Coffeescript is more forgiving than I thought with whitespace.

**Thanks to r.e.s. and Peter Taylor for some tips for making it a bit sleeker**
> 3 votes

# Answer
# Mathematica 19 17 27

`LongestCommonSequence` returns the longest non-contiguous subsequence of two strings. (Not to be confused with `LongestCommonSubsequence`, which returns the longest contiguous subsequence.

The following checks whether the longest contiguous subsequence is the first of the two strings. (So you must enter the shorter string followed by the larger string.)

```
LongestCommonSequence@##==#&

```

**Examples**

```
LongestCommonSequence@## == # &["", "z00"]
LongestCommonSequence@## == # &["z00", "z00"]
LongestCommonSequence@## == # &["anna", "banana"]
LongestCommonSequence@## == # &["Anna", "banana"]

```

True True True False

The critical test is the third one, because "anna" is contained non contiguously in "banana".
> 3 votes

# Answer
# PHP, 41 Bytes

prints 1 for true and nothing for false

```
<?=!levenshtein($argv[1],$argv[2],0,1,1);

```

If only insertions from word 1 to word 2 done the count is zero for true cases

levenshtein

Try it online!

## PHP, 57 Bytes

prints 1 for true and 0 for false

Creates a Regex

```
<?=preg_match(_.chunk_split($argv[1],1,".*")._,$argv[2]);

```

Try it online!
> 3 votes

# Answer
# Haskell, 36 bytes

```
(a:b)%(c:d)=([a|a/=c]++b)%d
s%t=s<=t

```

Try it online!

---

**37 bytes**

```
(.map concat.mapM(\c->["",[c]])).elem

```

Try it online!

I think `mapM` postdates this challenge. If we can assume the characters are printable, we can do

**36 bytes**

```
(.map(filter(>' ')).mapM(:" ")).elem

```

Try it online!

---

**37 bytes**

```
(null.).foldr(?)
c?(h:t)|c==h=t
c?s=s

```

Try it online!
> 3 votes

# Answer
## JavaScript (no regex), 45 bytes

```
y=>x=>(i=0,[...y].map(c=>c==x[i]&&i++),!x[i])

```

Should be called like

```
f(haystack)(needle)

```
> 3 votes

# Answer
# C - 74 71 64

This doesn't beat Peter Taylor's solution, but I think it's pretty fun (plus, this is a complete working program, not just a function)

```
main(int c,char**v){for(;*v[1]!=0;++v[1])v[2]+=*v[1]==*v[2];return*v[2];}

```

---

```
main(int c,char**v){for(;*v[1];++v[1])v[2]+=*v[1]==*v[2];return*v[2];}

```

---

```
main(c,v)char**v;{while(*v[1])v[2]+=*v[1]++==*v[2];return*v[2];}

```

And ungolfed:

```
main(int argc, char** argv){
   char * input = argv[1];
   char * test  = argv[2];

   // advance through the input string. Each time the current input
   // character is equal to the current test character, increment
   // the position in the test string.

   for(; *input!='\0'; ++input) test += *input == *test;

   // return the character that we got to in the test string.
   // if it is '\0' then we got to the end of the test string which
   // means that it is a subsequence, and the 0 (EXIT_SUCCESS) value is returned
   // otherwise something non-zero is returned, indicating failure.
   return *test;
}

```

To test it you can do something like:

```
./is_subsequence banana anna && echo "yes" || echo "nope"
# yes
./is_subsequence banana foobar && echo "yes" || echo "nope"
# nope

```
> 2 votes

# Answer
## Ruby ~~32~~ ~~30~~ 28

```
f=->a,b{b.match a.tr'','.*'}

```

This will return `MatchData` instance if `a` is subsequence of `b` or `nil` otherwise.

**Old version that find substring instead of subsequence**

## Ruby 15

```
f=->a,b{!!b[a]}

```

Using `String#[](str)` method that returns `str` if `str` is a substring of `self` and `!!` to return `Boolean` if returned value can be usable as boolean (and don't need to be `true` or `false`) then it can be only 13 chars:

```
f=->a,b{b[a]}

```

It will return `nil` if `a` is not a substring of `b`.
> 2 votes

# Answer
## Python, ~~66~~ ~~62~~ ~~59~~ 58 chars

Kind of a fun solution, definitely a neat problem.

```
def f(n,h,r=0):
 for c in h:r+=n[r:r+1]==c
 return r==len(n)

```
> 2 votes

# Answer
# SWI-Prolog, SICStus

The built-in predicate sublist/2 of SICStus checks whether all the items in the first list also appear in the second list. This predicate is also available in SWI-Prolog via compatibility library, which can be loaded by the query `[library(dialect/sicstus/lists)].`.

Sample run:

```
25 ?- sublist("","z00").
true.

26 ?- sublist("z00","z00").
true .

27 ?- sublist("z00","00z0").
false.

28 ?- sublist("aa","anna").
true .

29 ?- sublist("anna","banana").
true .

30 ?- sublist("Anna","banana").
false.

```

The byte count can technically be 0, since all we are doing here is querying, much like how we run a program and supply input to it.
> 2 votes

# Answer
# x86-16 machine code, ~~12~~ 10 bytes

**Binary:**

```
00000000: 41ac f2ae e303 4a75 f8c3                 A.....Ju..

```

**Unassembled listing:**

```
41          INC  CX                 ; Loop counter is 1 greater than string length
        SCAN_LOOP:
AC          LODSB                   ; load next char of acronym into AL
F2 AE       REPNZ SCASB             ; search until char AL is found
E3 03       JCXZ DONE               ; stop if end of first string reached
4A          DEC  DX                 ; decrement second string counter
75 F8       JNZ  SCAN_LOOP          ; stop if end of second string reached
        DONE:
C3          RET                     ; return to caller

```

Callable function. Input: `Y` string pointer in `SI`, length in `CX`. `X` string pointer in `DI`, length in `DX`. Output is `ZF` if `Truthy`.

**Example test program:**

This test program uses additional PC DOS API I/O routines to take multi-line input from `STDIN`.
> 2 votes

# Answer
# Red, 82 bytes

```
func[x y][parse/case y collect[foreach c x[keep reduce['to c 'skip]]keep[to end]]]

```

Try it online!
> 2 votes

# Answer
# Charcoal, ~~18~~ 17 bytes

```
ＦηＦ⁼ι∧θ§θ⁰≔Φθμθ¬θ

```

Try it online! Link is to verbose version of code. Uses Charcoal's default Boolean output of `-` for true, nothing for false. Explanation:

```
Ｆη

```

Loop over the characters of `Y`.

```
Ｆ⁼ι∧θ§θ⁰

```

See if this character is the next character of `X`.

```
≔Φθμθ

```

If so then remove that character from `X`.

```
¬θ

```

Were all the characters of `X` consumed?
> 2 votes

# Answer
# 05AB1E, 3 bytes

```
æQà

```

Try it online or verify all test cases.

Or alternatively:

```
æså

```

Try it online or verify all test cases.

With both programs the first input is \\$Y\\$ and the second input is \\$X\\$.

**Explanation:**

```
æ    # Get the powerset of the (implicit) input-string `Y`
 Q   # Check for each if it's equal to the (implicit) input-String `X`
  à  # And check if any are truthy by taking the maximum
     # (after which this result is output implicitly)

æ    # Get the powerset of the (implicit) input-String `Y`
 s   # Swap to take the (implicit) input-String `X`
     # (could also be `I` or `²` to simply take input)
  å  # Check if this string is in the powerset-list of strings
     # (after which this result is output implicitly)

```
> 2 votes

# Answer
# Regex (PCRE2 v10.35+), 25 bytes

```
^((.)(?*.*
(\3?+.*\2)))*

```

Attempt This Online!

Takes input as **X** followed by **Y**, delimited by a newline.

This abuses molecular lookahead `(?*`...`)` to save a byte. Instead of using a lazy quantifier `.*?` to advance only as far as necessary to find the next matching character, it greedily lets the regex engine do all the work by backtracking until it is able to match all of **X** in **Y** (or fail to, after trying all possibilities).

This beats mbomb007's Retina answer by 1 byte, though not when ported to .NET (in that it is 29 bytes – see below).

# Regex (Perl / PCRE / Java), 26 bytes

```
^((.)(?=.*
(\3?+.*?\2)))*

```

Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- Java

```
^                 # Anchor to start of string X
(
    (.)           # \2 = next character from X (starting at its start)
    (?=           # Atomic lookahead
        .*¶       # Skip to the beginning of string Y
        (         # \3 = concatenation of the following:
            \3?+  # previous value of \3, if set
            .*?   # Advance by as little as possible (minimum zero) to make the
                  # following match:
            \2    # Match the character we captured in \2
        )
    )
)*                # Iterate the above as many times as possible
¶                 # Assert that after doing the above, we've reached a newline,
                  # meaning the loop processed all of string X.

```

Taking the arguments in the opposite order takes **28 bytes**:

```
((.)(?=.*
(\3?+\2)).*)*
\3?$

```

Try it online! \- PCRE2

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

```
^((.)(?=.*
((?>\3?).*?\2)))*

```

Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- Java
**Try it online! \- .NET**

The uses an atomic group `(?>\3?)` instead of a possessive quantifier `\3?+` to add .NET compatibility.

## Regex (.NET), 31 bytes

```
(?<=(.)*)
(.*(?<-1>\1))*(?(1)^)

```

Try it online!

As a matter of curiosity (even though it doesn't beat the group-building method), here is a version using .NET's Balancing Groups feature.

```
(?<=(.)*)      # In a lookbehind, push each character of string X onto the \1
               # stack, going from right to left. There is no need to use a "^"
               # anchor, because the lookbehind is atomic and will lock in its
               # first greedy full match.
¶              # Assert that the next character is a newline, meaning that the
               # above processed the entirity of string X.
(
    .*         # Skip however many characters as needed to match the following:
    (?<-1>\1)  # Pop a capture off the \1 stack and match it. This is iterated
               # from left to right.
)*             # Iterate the above as many times as possible.
(?(1)^)        # Assert that the \1 stack is now empty (by asserting that if it
               # isn't, then we're at the start of the string – which is
               # impossible because we have at the very least matched a newline).

```

# Regex (Perl / PCRE / Java / Python`regex` / Ruby / .NET), 33 bytes

```
^((.)(?=.*
(?=(\4?))(\3.*?\2)))*

```

Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- Java
**Try it online! \- Python `import regex`
Try it online! \- Ruby**
Try it online! \- .NET

Copies the capture back and forth between `\3` and `\4` to avoid use of nested backreferences, adding Python and Ruby support (and as the lookahead is atomic, it's also another way of adding .NET support).

## \\$\large\textit{Anonymous functions}\\$

# Julia, ~~52~~ ~~51~~ 50 bytes

*-1 byte thanks to MarcMush*
*-1 byte thanks to MarcMush*

```
x->y->count(r"^((.)(?*.*
(\3?+.*\2)))*
",x*'
'y)>0

```

Attempt This Online!

Yep, Julia string literals can contain an unescaped raw newline!

Beats Simeon Schaub's answer by 2 bytes when both are converted to the same type of declaration, e.g. currying, as used here.

Of course, both could also be 2 bytes shorter with operator overloading.
> 2 votes

# Answer
# Factor \+ `math.combinatorics`, 19 bytes

```
[ all-subsets in? ]

```

Try it online!
> 2 votes

# Answer
# Haskell + hgl, 2 bytes

```
iS
```

Attempt This Online!

So this is a builtin. There are actually a couple of builtins. There's also `fiS` which is the same function but the arguments flipped, there `iSW eq` which how `iS` is defined internally. There's `fe<ss` which gets all subsequences of `y` and checks if `x` is among them. There's `ap eq<lSW` which tests if the longest common subsequence is equal to the second element.

But these are no fun. Let's have a true no builtins solution

# Regex based, 17 bytes

```
pP<rXx<ic".*"<m p

```

Also

```
pP<rXx<ic".*"<!<p

```

This works like all the other regex answers here. It adds `.*` between items and then matches a regex.

# Parser based, 15 bytes

```
pP<mF(aK h'<χ)

```

This works similarly to the regex answer. It replace every character in the string with a parser that matches anything ending in that character. It then sequences all the parsers and checks if there is any partial matches.

It's cheaper than the regex which is a little surprising.

# Reflections

The regex answer is the one with the most room for improvement.

* There should be functions that build and apply regexes all in one. It's silly to have to build and then apply the regex separately. This would save 3 bytes on the regex solution
* Hard to imagine a situation in which `<!<` is going to be useful. Here we can see it's not saving anything. Maybe this should be shortened, the docs should have some info about when it is useful.
* There should be more versions of `ic` and `is`. Some that add copies to the outside, and a versions that are mapped with pure like the regex answer.

With the above changes the regex answer could look like

```
pPX<icp".*"

```

The only other suggestion I have is that *maybe* `aK h'` should get a synonym. It's basically "ends with", which seems like a concept that might come up again.
> 2 votes

# Answer
## CoffeeScript 73

Here's an alternative CoffeeScript answer, using regexes instead of recursion:

```
z=(x,y)->a='.*';a+=c+'.*'for c in x;b=eval('/'+a+'/');(y.replace b,'')<y

```

If the haystack matches a very greedy regex constructed from the needle, it will be replaced with an empty string. If the haystack is shorter than it started, the needle was a subsequence.

Returns false when `x` and `y` are both empty strings. Think we need a philosopher to tell us if an empty string is a subsequence of itself!

(Posted as a separate answer from my previous because it feels different enough to justify it).
> 1 votes

# Answer
### PowerShell, 38

```
$args[1]-clike($args[0]-replace'','*')

```

Of course, any such regex- or pattern-matching-based solution has severe performance problems with longer strings. But since shortness is the criterion ...
> 1 votes

# Answer
A sort of anti-solution generating all subsequences of Y:

# Python 93

```
l=len(y)
print x in[''.join(c for i,c in zip(bin(n)[2:].rjust(l,'0'),y)if i=='1')for n in range(2**l)]

```
> 1 votes

# Answer
## APL (31)

String handling is a bit lacking in APL.

```
{(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N}

```

usage:

```
      {(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N} 'anna' 'banana'
1
      {(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N} 'Anna' 'banana'
0
      {(⊂'')∊N←⍵↓⍨¨1,⍨=/⊃¨⍵:~×⍴⊃N⋄∇N} '' 'banana'
1

```
> 1 votes

# Answer
# Python 132

Similar to Daniero's. Not the easiest solution, but it was fun to try. I'm new to Python, so I'm sure I could make it shorter if I knew a little bit more.

```
def f(i):
    s=x;j=0
    while j<len(s):t=~i%2;s=[s[:j]+s[j+1:],s][t];j+=t;i>>=1
    return s==y
print True in map(f,range(1,2**len(x)))

```
> 1 votes

# Answer
# **Python - 72**

```
def f(a,b):
 c=len(a)
 for i in b:a=a.replace(i,"",1)
 print len(a+b)==c

```
> 1 votes

# Answer
# Retina, 26 bytes (not competing)

The language is newer than the challenge. Byte count assumes ISO 8859-1 encoding. Input is taken on two lines with Y first.

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

```

**Try it online**
> 1 votes

# Answer
# Python (75 52)

```
s=lambda a,b:a==''or b>''and s(a[a[0]==b[0]:],b[1:])

```

Simple recursive solution. First time golfing, so any tips on whittling this down are much appreciated :)

Tested with the following:

```
assert s('anna', 'banana') == True
assert s('oo0', 'oFopp0') == True
assert s 'this', 'this is a string') == True
assert s('that', 'this hat is large') == True
assert s('cba', 'abcdefg') == False

```

Thanks to @lirtosiast for some clever boolean tricks.
> 1 votes

# Answer
# Java 8, ~~163~~ ~~162~~ ~~38~~ 35 bytes

```
a->b->b.matches(a.replace("",".*"))

```

-124 bytes by converting to Java 8, and pasting my answer from the duplicated challenge.

NOTE: Doesn't work if the input contains special regex-characters, but this would invalidate a lot of existing answers as well.

Try it online.

**Explanation:**

```
a->b->         // Method with two String parameters and boolean return-type
  b.matches(   //  Check if the second input matches the regex:
   a           //   The first input,
    .replace("",".*"))
               //   where every character is surrounded with ".*"

```

*For example:*

```
a="anna"
b="banana"

```

Will do the check:

```
"banana".matches("^.*a.*n.*n.*a.*$")

```
> 1 votes

# Answer
# PHP, ~~75~~ ~~65~~ 64 bytes

```
for(;$p=@strpos(_.$argv[2],$c=$argv[1][$i++],$p+1););echo""==$c;

```

takes input from command line arguments; prints `1` for true, empty string for false. Run with `-r`.

**explanation:**

* `strpos` returns `false` if needle `$c` is not in the haystack `$argv[2]` (after position `$p`),
causing the loop to break.
* `strpos` also returns `false` for an empty needle, breaking the loop at the end of `$argv[1]`.
* If `$argv[1]` is a subsequence of `$argv[2]`, `$c` will be empty when the loop breaks.
* `strpos` needs `@` to suppress `Empty needle` warning.
> 1 votes

# Answer
# Swift, 27

```
print(Y.range(of:X) != nil)

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 18 bytesSBCS

Full program. Prompts for Y then for X.

```
×≢(∊'.*'∘,¨⍞)⎕S⍬⊢⍞

```

Try it online!

prompt (for Y)

yield that (separates  from it)

`(``)⎕S⍬` search for occurrences of the following, yielding one empty list for each match:

prompt (for X)

`'.*'∘,¨` prepend `.*` to each character

**ϵ**nlist (flatten)

tally the number of matches

`×` sign of that
> 1 votes

# Answer
# APL(NARS), chars 46, bytes 92

```
{(⊂,⍺)∊(⊂''),↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}

```

test:

```
  h←{(⊂,⍺)∊(⊂''),↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}
  '' h 'z00'
1
  'z00' h 'z00'
1
  'z00' h '00z0'
0
  'aa' h 'anna'
1
  'anna' h 'banana'
1
  'Anna' h 'banana'
0

```

comment:

```
{(⊂,⍺)∊(⊂''),↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}
 ⍳¯1+2*k←≢w←⍵    this assign to w the argument and k argument lenght, it return 1..(2^k)-1 range
 {⍵⊤⍨k⍴2}¨      for each element of 1..(2^k)-1 convert in base 2 with lenght k (as the arg lenght)
 {⍵⊂w}¨         use the binary array above calculation for all partition argument
 ,/¨            concatenate each element of partition
 ↑¨             get the firs element of each element because they are all enclosed
 (⊂''),         add to the array the element (⊂'')
 (⊂,⍺)∊         see if (⊂,⍺) is one element of the array, and return 1 true o 0 false

```

How all you can see the comments are +- superfluous all is easy...

I have to say not understand why the last instruction is not "(,⍺)∊" in the place of "(⊂,⍺)∊" because for example in code

```
  q←{↑¨,/¨{⍵⊂w}¨{⍵⊤⍨k⍴2}¨⍳¯1+2*k←≢w←⍵}
  o q '123'
┌7──────────────────────────────────────┐
│┌1─┐ ┌1─┐ ┌2──┐ ┌1─┐ ┌2──┐ ┌2──┐ ┌3───┐│
││ 3│ │ 2│ │ 23│ │ 1│ │ 13│ │ 12│ │ 123││
│└──┘ └──┘ └───┘ └──┘ └───┘ └───┘ └────┘2
└∊──────────────────────────────────────┘
  o (,'3')
┌1─┐
│ 3│
└──┘

```

all you see array of 1 element (,'3') is the element of the set of instruction q '123', but

```
  o (,'3')∊q '123'
┌1─┐
│ 0│
└~─┘

```

return one array of unclosed 0 instead of number 1... for workaround that one has to write:

```
  o (⊂,'3')∊q '123'
1
~

```

that is the right result even if the element seems different because :

```
  o (⊂,'3')
┌────┐
│┌1─┐│
││ 3││
│└──┘2
└∊───┘

```

It is sure i make some error because i am not so smart... where is my error?
> 1 votes

# Answer
# JavaScript, 32 bytes

Repost of a port of Kevin's Java solution to a duplicate challenge, modified in case my choices for I/O weren't standards at the time this challenge was posted.

```
x=>y=>!!y.match([...x].join`.*`)

```

Try it online! (will update with this challenge's test cases when I get back to a computer)
> 1 votes

# Answer
# Perl 6, ~~34~~ 28 bytes

*-6 bytes thanks to nwellnhof*

```
{$!=S:g/<(/.*/;&{?/<{$!}>/}}

```

Try it online!

Anonymous code block that takes input curried, like `f(X)(Y)`. This does the familiar join by `.*` and evaluate as a regex as other answers, but takes a couple of shortcuts.

### Explanation:

```
{                          }  # Anonymous code block
 $!=            # Assign to $!
    S:g/<(/.*/  # Inserting .* between every character
              ;&{         }   # And return an anonymous code block
                 ?/      /    # That returns if the input matches
                   <{$!}>     # The $! regex

```
> 1 votes

# Answer
# Julia 1.0, 53 bytes

```
f(x,y)=(x==""||[x=x[2:end] for c=y if c==x[1]];x=="")

```

Try it online!
> 1 votes

# Answer
# Jelly, 3 bytes

```
ŒPi

```

Try it online!

Outputs `0` for false and a non-negative integer for true

## How it works

```
ŒPi - Main link. Takes X on the left and Y on the right
ŒP  - Powerset of X
  i - Index of y, or 0

```
> 1 votes

# Answer
# Husk, 2 bytes

```
€Ṗ

```

Try it online!

Having a single byte builtin for powerset is useful.
> 1 votes

# Answer
# MMIX, 40 bytes (10 instrs)

C strings.

```
00000000: 8302 0000 8303 0100 dc04 0203 30FF 0203  ............0...
00000010: 73FF FF01 2200 00FF 2301 0101 5b04 fff9  s..."...#...[...
00000020: 7300 0201 f801 0000                      s.......

```

# Disassembly

```
subseq  LDBU $2,$0,0        // loop: av = *a
        LDBU $3,$1,0        // bv = *v
        MOR  $4,$2,$3       // t0 = av && bv (MOR is faster than MUL)
        CMP  $255,$2,$3     // t1 = av <=> bv
        ZSZ  $255,$255,1    // t1 = !t1
        ADDU $0,$0,$255     // a += t1
        ADDU $1,$1,1        // b += 1
        PBNZ $4,subseq      // iflikely(t0) goto loop
        ZSZ  $0,$2,1        // a = !t0
        POP  1,0            // return a

```

Obvious algorithm, with only one branch!

For `wchar_t`, replace `LDBU` with `LDWU` (and similarly for `codepoint_t`); additionally, replace `ADDU $0,$0,$255` with `2ADDU $0,$255,$0` (`4ADDU` for codepoints), and `ADDU $1,$1,1` with `ADDU $1,$1,2` or `ADDU $1,$1,4`.
> 1 votes

# Answer
# Vyxal, 2 bytes

```
ṗc

```

Try it Online!
> 1 votes

# Answer
# K (ngn/k), ~~32~~ 18 bytes

```
~#*{(=/*'x;1)_'x}/

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `G`, 2 bytes

```
ʠ=

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

#### Explanation

```
ʠ=  # Implicit input
ʠ   # Powerset of the first input string
 =  # Vectorised equality check with the second input string
    # Check if any are true, and implicitly output

```
> 1 votes

# Answer
# Nekomata \+ `-e`, 2 bytes

```
S=

```

Attempt This Online!

```
S       Check if any subset of the first string
 =      is equal to the second string

```
> 1 votes

# Answer
## C, 120

```
main(i,c){char x[99],y[99];c=0;gets(y),gets(x);for(i=0;y[i]!='\0';)c+=y[i++]==x[c]?1:0;puts(x[c]=='\0'?"True":"False");}

```
> 0 votes

# Answer
## Javascript, 104 chars

```
function _(x,y){f=true;for(c in x){if(y.indexOf(x[c])>-1)y=y.replace(x[c],"");else{f=!f;break}}return f}

```

Ungolfed

```
function _(x,y){
f=true;
    for(c in x)
    {
        if(y.indexOf(x[c])>-1)
           y=y.replace(x[c],"");
        else {
            f=!f;
            break;
        }
    }
    return f;
}

```
> 0 votes

# Answer
# J (20 chars)

```
(<x)e.(#:i.2^#y)<@#y

```

The input is given in the variables `x` and `y`. It makes a list of all subsequences of `y`, so don't use it for very big strings.
> 0 votes

# Answer
# Python (72)

```
import itertools as I;any(tuple(X)==Z for Z in I.permutations(Y,len(X)))

```
> 0 votes

# Answer
## JavaScript (ES6), 42 bytes

Takes input `n` (needle) and `h` (haystack) in currying syntax `(n)(h)`.

```
n=>h=>!!RegExp(n.split``.join`.*`).exec(h)

```

### Test

```
let f =

n=>h=>!!RegExp(n.split``.join`.*`).exec(h)

console.log(f(''    )('z00'   )); // true
console.log(f('z00' )('z00'   )); // true
console.log(f('z00' )('00z0'  )); // false
console.log(f('aa'  )('anna'  )); // true
console.log(f('anna')('banana')); // true
console.log(f('Anna')('banana')); // false
```
> 0 votes

# Answer
# Pyth, 5 bytes

```
}hQye

```

Explanation

```
}hQye
 hQ       The first input...
}         ... is an element of...
   y      ... the power set...
    eQ    ... of the second input.

```
> 0 votes

# Answer
## REXX, 76 bytes

```
o=1
do while x>''
  parse var x a+1 x
  parse var y(a)b+1 y
  o=o&a=b
  end
return o

```

Note that x and y are consumed by this routine. Readability is impaired by skipping a lot of whitespace and parentheses.
> 0 votes

# Answer
# Python 2, 47 bytes

```
x,y=map(list,input())
while x:y.remove(x.pop())

```

Try it online!

Takes two quote-delimited strings via STDIN as input.

Output is by presence or absence of an error, which is allowed per meta consensus.

Explanation:

```
             # get arguments from STDIN
             input()
    # convert each argument to a list
    map(list,.......)
# split arguments into two variables
x,y=..................

# while x still has elements
while x:
                 # remove the final element of x and return its value
                 x.pop()
        # remove the first matching item in y
        # this will error if there is no matching element
        y.remove(.......)

# if the loop is exited without error, all elements in x were in y

```
> 0 votes

# Answer
# Japt, 4 bytes

Repost from a duplicate challenge.

Takes input in reverse order (`Y`, then `X`).

```
à øV

```

Try it
> 0 votes

# Answer
# Pyth, 5 bytes

```
}hQye

```

Try it online!

---

```
Pyth   | Explanation
-------+------------------------------------------
}hQye  | Full code
}hQyeQ | "       " with implicit variables
-------+------------------------------------------
}      | return whether arg0 is an element of arg1
 hQ    |  first element of input
   y   |  powerset of
    eQ |   last element of input

```
> 0 votes

# Answer
# Lua, 85 68 66 bytes

```
_,b=...for c in (...):gmatch"."do b=b:gsub(c,"",1)end print(b=="")

```

Try it online!

### Explanation

`...` is the variable argument operator, it returns all remaining arguments to the current function (the top-level block in this case). We can force it to return just one variable by encasing it in parentheses.

`gmatch()` is a pattern-matching function which returns an iterator function, we use it to loop over every character in the input string.

`gsub()` is a substitution function, we use it to clear matched characters from the subset contender. The extra parameter is the number of substitutions to make, 1 in this case.
> 0 votes

# Answer
# Zsh `-o glob_subst`, 14 bytes

```
>:$1>${2///*}*

```

Try it online!

Explanation:

* `>:$1`: copy stdin to a file named `:` and the first argument. The colon ensures that we don't try to create a file with an empty name in the case of an empty string as input. Since we don't take any input from stdin, this just creates an empty file.
* `>${2///*}*`: try to copy stdin (again) to a file that matches the pattern resulting from the expansion of `${2///*}*` If no such file exists, an error will occur. The `-o glob_subst` ensures that the expanded value is treated as a pattern. Otherwise, it will be treated as a literal string. Alternatively, this option can be removed and `${~2///*}*` used instead for +1 byte.
    + `${2}`: take the second argument
    + `///*`: replace every empty string with an asterisk; this results in `abc` -\> `*a*b*c`
    + append another asterisk. Asterisks simply mean "match any sequence
> 0 votes

# Answer
# Vyxal, 6 bytes

```
ṗƛṅ;$c

```

Try it Online!
> 0 votes

# Answer
# brev, 78 bytes

```
(define(s(x . xs)y)(aif(memq x y)(s xs(cdr it))#f))(define(s'()y)#t)

```

68 to define `s`, but you've got to call it as `(as-list s)` to handle string input.

```
(define (s (x . xs) y)
  (aif (memq x y) (s xs (cdr it)) #f))

(define (s '() y) #t)

(map (fn (apply (as-list s) x))
     '((""     "z00")
       ("z00"  "z00")
       ("z00"  "00z0")
       ("aa"   "anna")
       ("anna" "banana")
       ("Anna" "banana")))

```

Bonus! Regex version 50 bytes:

```
(fn(with(strse x"."(conc(m 0)".*"))(strse? y it)))

```
> 0 votes

---
Tags: code-golf, string, decision-problem
---


title: Print number triangle

text:
# Question
Title: Print number triangle
Given a number `N`, output a NxN right angled triangle, where each row `i` is filled with numbers up to `i`.

**Example**

**n** = 0

(no output)

**n** = 4

```
1
1 2
1 2 3
1 2 3 4

```

**n** = 10

```
1
1 2
1 2 3
.
.
.
1 2 3 4 5 6 7 8 9 10

```

(no alignment needed)

**n** = N

```
1
1 2
1 2 3
.
.
.
1 2 3 4 .... N

```

There is no trailing space at the end of each line.

Least number of bytes wins, and standard loopholes are not allowed.

# Answer
> 20 votes
# Joe, 5 3 bytes (+2 or +3 for `-t` flag)

Well, apparently I didn't utilize the full potential of Joe. This was possible back when I first posted this.

```
\AR

```

Here, `R` gives the range from 0 to n, exclusive. Then `\A` takes successive prefixes of it (`A` is the identity function). Examples:

With `-t` flag (note: this is now the standard output even without the flag):

```
   (\AR)5
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
   \AR5
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
   \AR2
0
0 1
   \AR1
0
   \AR0

```

Without it:

```
   \AR5
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
   (\AR)5
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
   \AR2
[[0], [0, 1]]
   \AR1
[[0]]
   \AR0
[]

```

---

The rules got changed a bit. My old code didn't behave correctly with N =0. Also, now output could be just a nested list, so `-t` can be dropped.

```
1R1+R

```

Now, `Rn` gives a range from 0 to n, exclusive. If given 0, it returns an empty list. `1+` adds 1 to every element of that range. `1R` maps the values to ranges from 1 to x. Empty liats, when mapped, return empty lists.

Example output:

```
   1R1+R0
[]
   1R1+R5
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

```

Update: I just noticed something. The function automatically maps to rank 0 elements. The following example is run with `-t` flag.

```
   1R1+R3 5 8
1
1 2
1 2 3

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

```

---

Old: 5 bytes (with the `-t` flag)

```
1R1R

```

This is an anonymous function which takes in a number, creates a list from 1 to N (`1Rn`) and maps those values to the preceding range, giving a range from 1 to x for each item of range 1 to N.

The `-t` flag gives output as a J-like table.

```
   1R1R5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

Note : the language is very new and not complete, but the latest version was released before this challenge.

# Answer
> 10 votes
# Python 3, ~~48~~ 45 bytes

```
f=lambda n:n and[f(n-1),print(*range(1,n+1))]

```

Hooray for side effects.

# Answer
> 8 votes
## APL, 5

```
⍪⍳¨⍳⎕

```

creates a vector 1..n and for each element another such vector.

Then ⍪ makes a column out of all vectors. This avoids the problem with trailing blanks.

Try it on tryapl.org

---

Older solution:

```
{⎕←⍳⍵}¨⍳⎕

```

Creates a vector 1..n

{⎕←⍳⍵} is a function that outputs for each (¨) element a vector 1..n on a separate line

This one can't be tried on tryapl.org unfortunately, because ⎕← doesn't work there.

# Answer
> 6 votes
# J, 27 bytes

J is not good with non-array numeric output. This function creates a properly formatted string from the numbers.

```
   ;@(<@,&LF@":@:>:@:i.@>:@i.)

   (;@(<@,&LF@":@:>:@:i.@>:@i.)) 4
1
1 2
1 2 3
1 2 3 4

```

Try it online here.

# Answer
> 6 votes
# PHP, 53 Bytes

Edit 2: Ismael Miguel suggested reading from input instead of defining a function, so the score is now 53 bytes for PHP:

```
for($a=1;@$i++<$n=$argv[1];$a.=" ".($i+print"$a\n"));

```

And once again, it can be improved if PHP is configured to ignore errors (52 bytes):

```
for($a=1;$i++<$n=$argv[1];$a.=" ".($i+print"$a\n"));
for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n"));

```

---

Edit: Austin suggested a 60 bytes version in the comments:

```
function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}

```

Which can be improved if we doesn't display PHP errors (59 bytes):

```
function f($n){for($a=1;$i++<$n;$a.=" ".($i+print"$a\n"));}

```

`$a` stores the next line that will be printed, and each time it's printed a space and the next number (`print` always returns `1`) are concatened to it.

---

Recursive functions (65 bytes):

```
function f($n){$n>1&&f($n-1);echo implode(' ',range(1,$n))."\n";}
function f($n){$n>1&&f($n-1);for(;@$i++<$n;)echo$i,' ';echo"\n";}   // Using @ to hide notices.

```

Shorter recursive function, with error reporting disabled (64 bytes):

```
function f($n){$n>1&&f($n-1);for(;$i++<$n;)echo$i,' ';echo"\n";}

```

Even shorter recursive function, with error reporting disabled and an empty line before real output (62 bytes):

```
function f($n){$n&&f($n-1);for(;$i++<$n;)echo$i,' ';echo"\n";}

```

---

Just for fun, non-recursive fucntions:

```
function f($n){for($i=0;$i<$n;print implode(' ',range(1,++$i))."\n");}    // 70 bytes
function f($n){for(;@$i<$n;print implode(' ',range(1,@++$i))."\n");}      // 68 bytes, hiding notices.
function f($n){for(;$i<$n;print implode(' ',range(1,++$i))."\n");}        // 66 bytes, error reporting disabled.

```

# Answer
> 5 votes
# CJam, ~~13~~ 12 bytes

```
ri{),:)S*N}/

```

**How it works**:

```
ri{       }/     "Run the block input number of times with iteration index from 0 to N-1";
   )             "Increment the iteration index (making it 1 to N)";
    ,            "Get an array of 0 to iteration index";
     :)          "Increment each of the above array members by 1";
       S*        "Join all above array numbers with space";
         N       "Add a new line. After all iterations, things are automatically printed";

```

Try it online here

# Answer
> 4 votes
# JavaScript (ES6) 49 ~~52~~

Such a simple task, I wonder if this can be made shorter in JS (Update: yes, using recursion)

Recursive 49

```
f=n=>alert((r=w=>n-i++?w+'\n'+r(w+' '+i):w)(i=1))

```

Iteraive 52

```
f=n=>{for(o=r=i=1;i++<n;o+='\n'+r)r+=' '+i;alert(o)}

```

# Answer
> 4 votes
# Pyth, 9 bytes

```
VQjdr1hhN

```

Really thought that this can be done shorter, but it doesn't seem so.

Try it online.

```
            Q = input()
VQ          For N in [0, 1, ..., Q-1]:
    r1hhN       create list [1, ..., N+1+1-1]
  jd            print joined with spaces

```

# Answer
> 4 votes
# Java, ~~85~~ 84 bytes

This is surprisingly short in Java.

```
void a(int a){String b="";for(int c=0;c++<a;System.out.println(b+=(c>1?" ":"")+c));}

```

Indented:

```
void a(int a){
    String b="";
    for(int c=0;
        c++<a;
        System.out.println(
                b+=(c>1?" ":"")+c
        ));
}

```

1 byte thanks to Bigtoes/Geobits

# Answer
> 3 votes
# \>\<\> (Fish), 40 37 + 3 = 40 bytes

```
&1>:&:&)?;1\
(?v:n" "o1+>}:{:@
ao\~1+

```

Once again, \>\<\> does decently well at another number printing exercise. Run with the `-v` flag for input, e.g.

```
py -3 fish.py -v 4

```

## Explanation

```
&               Put n in register
1               Push 1 (call this "i")

[outer loop]

:&:&)?          If i > n...
;                 Halt
1                 Else push 1 (call this "j")

[inner loop]

}:{:@(?         If j > i...
~1+ao             Pop j, print newline, increment i and go to start of outer loop
:n" "o1+          Else print j, print a space, increment j and go to start of inner loop

```

# Answer
> 3 votes
# Prolog - 119

```
h(N):-setof(X,(between(1,N,K),setof(Y,between(1,K,Y),X)),[L]),k(L),nl,fail.
k([A|B]):-write(A),(B=[];write(" "),k(B)).

```

# Answer
> 3 votes
**Python 2 - ~~62~~ ~~54~~ 65 bytes**

```
def f(n):
 for x in range(n):print' '.join(map(str,range(1,x+2)))

```

# Answer
> 3 votes
## J, 9 characters

As a tacit, monadic verb.

```
[:":\1+i.

```
* `i. y` – the numbers from `0` to `y - 1`.
* `1 + i. y` – the numbers from `1` to `y`.
* `": y` – the vector `y` represented as a string.
* `":\ y` – each prefix of `y` represented as a string.
* `":\ 1 + i. y` – each prefix of the numbers from `1` to `y` represented as a matrix of characters.

# Answer
> 2 votes
# Python 2 - 72

```
>>> def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N))
...
>>> p(5)
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

# Answer
> 2 votes
# C (with no loops, yeah!) - 72 bytes

```
b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}}

```

This creates a function `r(n)` that can be used this way:

```
main(){ r(5); }

```

See it in action, here on tutorialspoint.com

It requires a very few tricks easily explained. I think it can be greatly improved.

# Answer
> 2 votes
# Perl, 28

Reads the parameter from stdin.

```
@x=1..$_,print"@x
"for 1..<>

```

From the command line:

```
perl -E'$,=$";say 1..$_ for 1..<>'

```

but I don't now how to count that (probably between 25 and 29).

# Answer
> 2 votes
# Thunno 2 `N`, 5 bytes

```
RRıðj

```

Attempt This Online!

#### Explanation

```
RRıðj  # Implicit input    ->  4
R      # Range [1..n]      ->  [1,2,3,4]
 R     # Range of each     ->  [[1],[1,2],[1,2,3],[1,2,3,4]]
  ı    # To each list:
   ðj  #  Join by spaces   ->  ["1","1 2","1 2 3","1 2 3 4"]
       # Join by newlines  ->  "1\n1 2\n1 2 3\n1 2 3 4"
       # Implicit output

```

# Answer
> 2 votes
# Julia 1.0, 34 bytes

```
~n=1:n.|>x->println(join(1:x,' '))

```

Try it online!

# Answer
> 1 votes
## Python

```
import string
N,s=int(input()),list(string.digits)
for i in range(1,N+1):
    print(' '.join(s[1:i+1]))

```

# Answer
> 1 votes
# Go, ~~93~~ ~~81~~ ~~78~~ ~~93~~ 90 bytes

```
func r(n int)(s string){s=string(n+48);if n!=1{s=r(n-1)+" "+s};println(s);return}

```

## Current ungolfed

```
func r(n int) (s string) {
    // Convert n to a string, we do not have to initialize s since
    // we hijacked the return value.
    // Numbers in the ascii table starts at 48
    s = string(n | 48)
    // Unless we are on our last iteration, we need previous iterations,
    // a space and our current iteration
    if n != 1 {
        // Collect the result of previous iteration for output
        s = r(n-1) + " " + s
    }
    println(s)
    // We can use a naked return since we specified the
    // name of our return value in the function signature
    return
}

```

If we need to handle N \> 9 we can use the following at 78 bytes, however it requires importing the `fmt` package.

```
func r(n int)(s string){s=Sprint(n);if n!=1{s=r(n-1)+" "+s};Println(s);return}

```

If we include the import statement I'm now back at my initial ~~93~~ ~~92~~ 90 bytes

```
import."fmt";func r(n int)(s string){s=Sprint(n);if n>1{s=r(n-1)+" "+s};Println(s);return}

```

Test it online here: http://play.golang.org/p/BWLQ9R6ilw

The version with `fmt` is here: http://play.golang.org/p/hQEkLvpiqt

# Answer
> 1 votes
# Golfscript 14

```
,{2+,1>' '*n}/

```

Expects the input number to be present on the stack.

Online example: link

# Answer
> 1 votes
# Perl: 34 characters

```
print"@$_\n"for map[1..$_],1..$_;

```

This code gets the input number supplied through the special variable `$_`.

# Answer
> 1 votes
# C, 89 characters

```
// 90 characters
f(int n){int a=1,b;for(;n--;++a){for(b=0;b<a;++b)printf("%c%d",(!!b)*' ',b+1);puts("");}}

```

To eliminate confusion about `puts("");`. This simply prints a newline character (as seen here):

> Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not).

I got it slightly shorter with @TheBestOne's java algorithm:

```
// 89 characters
f(int a){char b[999]="",*p=b+1;int c=0;for(;a--&&(sprintf(b,"%s %d",b,++c)&&puts(p)););}

```

# Answer
> 1 votes
# Clip, 16

```
Jm[ijkw,1iwS},1n

```

## Explanation

```
J                   .- join with newlines                           -.
 m[i        },1n    .- map numbers from 1 to numeric value of input -.
    jkw   wS        .- join with spaces                             -.
       ,1i          .- numbers from 1 to index                      -.

```

# Answer
> 1 votes
# Bash+coreutils, 26 bytes

```
seq $1|sed "x;G;s/\n/ /;h"

```
* `seq` simply generates the numbers 1 to n
* `sed` saves the entire output for a given line in the hold space, and then appends the next line to it.

# Answer
> 1 votes
# ZX / Sinclair BASIC - 39 bytes

ZX Basic uses 1 byte per keyword (all the uppercase words), so helps to keep the byte size down a bit...

```
1 INPUT n:FOR i=1 TO n:FOR j=1 TO i:PRINT j;" ";:NEXT j:PRINT:NEXT i

```

Using n = 8

# Answer
> 1 votes
# R, 28

```
for(i in 1:scan())print(1:i)

```

# Answer
> 1 votes
# TI-Basic, 28 bytes

```
Input N
For(I,1,N
randIntNoRep(1,N->L1
SortA(L1
Disp L1
End

```

# Answer
> 1 votes
# Haskell, 62 57 bytes

```
e=enumFromTo 1
f=putStr.unlines.map(unwords.map show.e).e

```

Point-free style. Usage example:

```
Prelude> f 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

# Answer
> 1 votes
# C++, 130 bytes

To provide N, provide that many arguments on the command-line (the arguments don't matter, just the count of arguments).

```
#include <stdio.h>
#define printf P
int main(int c, char**){if(int x=c-1){main(x--,0);P("1");for(;x;--x){P(" %d",c-x);}P("\n");}}

```

# Answer
> 1 votes
# C# - 94 bytes

Written as an anonymous function that returns a string, which doesn't seem to be disallowed by the spec.

```
n=>String.Join("\n\n",Enumerable.Range(1,n).Select(l=>String.Join(" ",Enumerable.Range(1,l))))

```

Here's an ungolfed version (comments are read in BDCA order):

```
n =>
    String.Join("\n\n",                    //...then join it together with newlines.
        Enumerable.Range(1, n).Select(l => //For each l from 1 to n, ...
                String.Join(" ",              //...and join it with spaces, ...
                    Enumerable.Range(1, l)    //...get the range from 1 to l, ...

```

# Answer
> 1 votes
# Scala, 73 65 62 bytes

```
(n:Int)=>print(1 to n map(1 to _ mkString " ") mkString "\n")

```

**Ungolfed**

```
def printNumberTriangle(n: Int): Unit = {
  def rowString(m: Int): String = 1.to(m).mkString(" ")
  print(1.to(n).map(rowString).mkString("\n"))
}

```

# Answer
> 1 votes
# Mathematica, 32

```
Print@Row[Range@i," "]~Do~{i,#}&

```

# Answer
> 1 votes
# JavaScript, 73

```
n=5;for(i=1,s='';i<=n;i++)for(j=1;j<=i;j++)s+=j+(j==i?"\n":' ');alert(s);

```

# Answer
> 1 votes
### Excel VBA, 97 bytes

```
n = InputBox("n")
For i = n To 1 Step -1
For j = n To 1 Step -1
Cells(i, j) = j
Next j
n = n - 1
Next i

```

When executed you are prompted for n and the resulting triangles are displayed on the spread sheet:

# Answer
> 1 votes
# JavaScript, 92 bytes

```
var x=function(o){for(var r=1;o>=r;r++){for(var a="",f=1;r>=f;f++)a+=f+" ";console.log(a)}};

```

usage: `x(5)`

# Answer
> 1 votes
# awk, 27 bytes

```
{for(n=$0;n>=$i=++i;)print}

```

Got it working with some tweaks.

### Example usage and output

```
me@home:~$ echo 0 | awk '{for(n=$0;n>=$i=++i;)print}'
me@home:~$ echo 1 | awk '{for(n=$0;n>=$i=++i;)print}'
1
me@home:~$ echo 2 | awk '{for(n=$0;n>=$i=++i;)print}'
1
1 2
me@home:~$ echo 12 | awk '{for(n=$0;n>=$i=++i;)print}'
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12

```

# Answer
> 1 votes
**C,88 bytes**

```
f(n,i,j,t){i=j=1;for(;i<=n;){t=j;printf("%d%c",t,j==i?(++i&&(j=1))*'\n':(++j||1)*' ');}}

```

Usage:

```
f(10);

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

```

# Answer
> 1 votes
# tcl, 76

```
time {set p "";set j 1;while \$j<=[incr i] {set p $p\ $j;incr j};puts $p} $n

```

Testable on http://rextester.com/FPJXC1708

Is the first line accountable? It is not part of the algorithm, only serves for acquiring input.

# Answer
> 1 votes
# Perl 6, 24 bytes

```
{say ~$_ for [\,] 1..$_}

```

# Answer
> 1 votes
# Jelly, 3 bytes

```
RRG

```

How it works:

```
RRG
R     Inclusive Range, 3 -> [1, 2, 3]
 R    Inclusive Range for all elements, [1, 2, 3] -> [[1], [1, 2], [1, 2, 3]]
  G   Attempt to format as grid

```

Try it online!

# Answer
> 1 votes
# Pushy, 4 bytes

```
:Lh_

```

**Try it online!**

This works by building the stack up to the final line, step-by-step, and printing the stages:

```
:    \ Input times do (this consumes input):
Lh   \  Push stack length + 1
_    \  Print stack items, space separated.

```

# Answer
> 1 votes
# J, 14 bytes

```
":@>@<@:>:\@i.

```

Usage:

```
   f =. ":@>@<@:>:\@i.
   f 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

**Explanation**:

```
   i.4                      N.B.  i.n = list of numbers up to n
0 1 2 3

   >:@i.4                   N.B.  >:n = increment n
1 2 3 4

   >:\@i.4                  N.B.  >:\n = increment prefixes of n
1 0 0 0
1 2 0 0
1 2 3 0
1 2 3 4

   <@:>:\@i.4               N.B.   < = Box, <@:>:\ = Box the incremented prefixes of n
+-+---+-----+-------+
|1|1 2|1 2 3|1 2 3 4|
+-+---+-----+-------+

   ":@>@<@:>:\@i.4          N.B.   ":@> = String format each opened box (ensures no zeros or spaces appear at the end of each line).
1
1 2
1 2 3
1 2 3 4

```

# Answer
> 1 votes
# Noether, 39 bytes

```
I~A{A0>}{A(i1+~i(j1+~jP" "P£)"
"P0~ji)}

```

**Try it here!**

**Explanation:**

```
I~A   - Push User Input onto the stack and store in variable A
{A0>} - If A>0
{     - Then do
A(    - loop until top of stack equals A
i1+~i - Increment i
(     - loop until top of stack equals i
j1+~j - Increment j
P     - Print top of stack (j)
" "   - Push the string " " onto stack
P     - Print top of stack (" ")
£     - Pop top of stack
)     - End loop
"\n"  - Push the string "\n" onto stack
P     - Print top of stack
0~j   - Set variable j to zero
i     - Push i onto stack
)     - End loop

```

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

```
: f 1+ 1 do i 1+ 1 do i . loop cr loop ;

```

Try it online!

# Answer
> 1 votes
# Vyxal `j`, 4 bytes

```
ɾɾvṄ

```

Try it Online!

### Explained

```
ɾɾvṄ
rr   # range over range over input
  v  # vectorise
   Ṅ # join list by spaces

```

`j` flag joins by newlines

# Answer
> 1 votes
# Arturo, 30 bytes

```
$=>[loop map&=>[@1..&]=>print]

```

Try it!

# Answer
> 0 votes
# C++

```
int main()
{
   cout << "Enter N:";
   int N;
   cin >> N;

    for(int i=1; i <= N; i++)
    {
         for(int j=1; j<=i; j++)
            {
              cout << j;
            }
       cout << endl;
    }

  return 0;
}

```

# Answer
> 0 votes
**Python 2 - 60 61 53 bytes**

```
k='1'
for i in range(2,input()+2):print k;k+=' '+`i`

```

With thanks to Sp3000

# Answer
> 0 votes
**Javascript, 83**

Not to happpy about this one

```
n=9;r='';for(i=1;i<n+2;i++){for(a=1;a<i;a++){r+=a+' '}r=r.slice(0,-1)+'\n'}alert(r)

```

Pretty straight forwards

`r='';` so javascript doesn't add the value as numbers

`r.slice(0,-1)+'\n'`remove last space and add a line end

Edit: info

First I was trying to use A030512(int seq) but that failed n\>10

# Answer
> 0 votes
# k, 8

```
1+!:'1+!

```

I need to add 27 characters so I'm just going to type some nonsense here.

```
k)!5
0 1 2 3 4

k)1+!5
1 2 3 4 5

k)!:'1+!5
,0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

k)1+!:'1+!5
,1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

# Answer
> 0 votes
# Ruby - 51

```
r=->(n){(1..n).each{|i|puts (1..i).to_a.join(" ")}}

```

Sample output:

```
r[5] # 1
     # 1 2
     # 1 2 3
     # 1 2 3 4
     # 1 2 3 4 5

r[7] # 1
     # 1 2
     # 1 2 3
     # 1 2 3 4
     # 1 2 3 4 5
     # 1 2 3 4 5 6
     # 1 2 3 4 5 6 7

```

# Answer
> 0 votes
# VBA, 116 bytes

```
Function n(m As Integer)
If m > 0 Then
For a = 1 To m
n = n & " " & a
Next
Debug.Print n(m - 1)
End If
End Function

```

# Answer
> 0 votes
# And the loser is... Pascal! ~~178~~ 148 bytes

Sidenote: this isn't golfed at all, besides newlines and spaces. I haven't coded in Pascal for more than 10 years, so I used it just for the memories.

Golfed:

```
program p;procedure p(n:integer);var i,j:integer;begin for i:=1 to n do begin for j:=1 to i do begin write(j); end; writeln; end end;begin p(5);end.

```

Ungolfed:

```
program p;
procedure p(n:integer);
var i,j:integer;
begin
    for i:=1 to n do begin
        for j:=1 to i do begin
            write(j);
        end;
        writeln;
    end
end;
begin
    p(5);
end.

```

# Answer
> 0 votes
**Python 2 - ~~57~~ 61 bytes**

Had another idea. Only bad thing is the leading space.

```
def f(n):
 s=''
 for x in range(n):s+=' %s'%(x+1);print s[1:]

```

example output:

```
>>> def f(n):
...  s=''
...  for x in range(n):s+=' %s'%(x+1);print s[1:]
...
>>> f(8)
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

```

# Answer
> 0 votes
**Golfscript - 41 chars**

```
"#{STDIN.gets}"~.0={}{)}if,{,{)}%" "*}%n*

```

How it works:

"#{STDIN.gets}" -\> Read a string from input

"~" -\> Evaluate the input

".0=" -\> Create a clone of the input and check if it's zero

"{}{)}if" -\> If it's zero, do nothing, else add one to the number

",{,{)}%" "\*}%" -\> Create a list from 0 to N, loop through it and create new lists and do other stuff that I don't have time to explain.

"n\*" -\> Display it nicely

# Answer
> 0 votes
# ARM assembly 485 bytes

```
.global main
main:
    mov r0, #10
    mov r1, #1
    bl triangle

    mov r0, #10
    bl putchar

    mov r7, #1
    swi 0

triangle:
    cmp r1, r0
    movgt pc, lr
    push {r0,r1,lr}
    mov r0, r1
    mov r1, #1
    bl row
    mov r0, #10
    bl putchar
    pop {r0,r1,lr}
    add r1, r1, #1
    b triangle

row:
    cmp r1, r0
    movgt pc, lr
    push {r0,r1,lr}
    ldr r0, =numFormat
    bl printf
    pop {r0,r1,lr}
    add r1, r1, #1
    b row

numFormat:
    .asciz "%d "

```

called using the subroutine `triangle`, register `r0` holds the limit and `r1` holds the starting value.

tested on Raspberry Pi and Android

# Answer
> 0 votes
# Java 8 - 293 chars

Golfed:

```
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
public class T{public static void main(String[] a){int n=10;System.out.println(IntStream.range(1,n+1).boxed().map(i->IntStream.range(1,i+1).boxed().map(j->""+j).collect(joining(" "))).collect(joining("\n")));}}

```

Ungolfed:

```
    import java.util.stream.*;
    import static java.util.stream.Collectors.joining;

    public class T {
        public static void main(String[] a){
            int n=10;

            System.out.println(
                 IntStream.range(1,n+1)
                          .boxed()
                          .map(i -> IntStream.range(1,i+1)
                                             .boxed()
                                             .map(j -> ""+j)
                                             .collect(joining(" ")))
                          .collect(joining("\n")));
        }
    }

```

Example output, n = 10:

```
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

```

# Answer
> 0 votes
# PHP (65 bytes):

This is pretty simple to do in php:

```
for(;$i++<$_GET[n];$_[]=join(' ',range(1,$i)));echo@join('
',$_);

```

This probably may output an empty string or the '\0' char or worst if you use `0` (there is no control on it).

This is because `$_` will be `null`when you use `0` and PHP will output `null` (which may output any of the said before).

---

There is another aproach (61 bytes):

```
foreach(range(1,$_GET[n])as$v)echo join(' ',range(1,$v))."
";

```

But it can't handle the `0` in the expected way.

# Answer
> 0 votes
## Dyalog APL, 11 characters

Assumes `⎕IO←1`.

```
(⍕↑)⍤0 1⍨⍳⎕

```
* `⍕⍵` represented as a string.
* `⍺↑⍵` items taken from .
* `⍺(⍕↑)⍵` items taken from , the result represented as a string.
* `⍺(⍕↑)⍤0 1⍵` – The previous expression, but executed for each item in  and each vector in .
* `(⍕↑)⍤0 1⍨⍵` – The previous expression with both arguments taken from .
* `(⍕↑)⍤0 1⍨⍳⍵` – The previous expression applied to the integers from `1` to .
* `(⍕↑)⍤0 1⍨⍳⎕` – The previous expression with input taken from the user.

# Answer
> 0 votes
# K, 17 bytes

```
(`0:" "/$1+!)'1+!

```

Doing this sort of formatted output isn't very convenient in K. I used the "join" form of `/` from k5 to join elements of each vector with spaces. Try it with oK.

A nice thing about this solution is that it is in "tacit" form, so there's no need to create a function wrapper. Just append the argument N and suppress the result with `;`:

```
  (`0:" "/$1+!)'1+!5;
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

# Answer
> 0 votes
**Powershell v2 number of Characters : 567**

```
   function Build-Triangle
    {
         [CmdletBinding()]
         param(
            [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
            [int]$n
        )

        begin {}
        process
        {
            [int]$cnt = 1
            if ( $n -gt 0 )
            {
                while ( $cnt -le $n )
                {
                    $string += $cnt.ToString() + " "
                    Write-Output -InputObject $string
                    $cnt++
                }
            }
        }
        end {}
    }

    Build-Triangle -n 10 | Measure-Object
    0 | Build-Triangle
    11 | Build-Triangle
    # just for kicks make the triangle upside down
    11 | Build-Triangle  | Sort-Object -Descending
    # find out how big the function is
    Get-Content Function:\Build-Triangle | Measure-Object -Word -Character -Line

```

# Answer
> 0 votes
## C# - 92 bytes

```
void f(int n){for(int i=0;i++<n;)Console.WriteLine(string.Join(" ",Enumerable.Range(1,i)));}

```

Nothing fancy, just a packed function.

# Answer
> 0 votes
# JavaScript, 73 chars

Not even trying to compare with the others here, just your typical first post:

```
for(n=prompt(),i=1;n>=i;i++){var l="";for(j=1;j<=i;j++)l+=" "+j;alert(l)}

```

# Answer
> 0 votes
# PowerShell -  ~~42~~ 32bytes

*Edit: AdmBorkBork reports that we can save many bytes by using a complete script, and assuming a default delimiter!*

```
 param($n)0..$n-gt0|%{"$(1..$_)"}

```

Never done any serious PowerShell, just felt I might learn something from this, and indeed I did. *Old 42byte code:*

```
function k($n){0..$n-gt0|%{1..$_-join" "}}

```

Defines a *function* `k` which takes an input `$n`, creates a range from `0` through to `$n`, filters for entires greater than `0`, then creates a range from `1` to each remaining value, and joins these with a space. Example out:

```
PS > k 3
1
1 2
1 2 3
PS > k 0
PS >

```

Alternatively, you can define a *filter*, which will print as many triangles as you want.

```
filter z{0..$_-gt0|%{1..$_-join" "}}

PS > 3,0,2|z
1
1 2
1 2 3
1
1 2
PS >

```

# Answer
> 0 votes
# Element, 20

```
_'[1+2:'.2:`\ ."\
`]

```

The main idea is that the stacks contain a string and a number. We repeatedly increment the number and append it to the string, printing the result. Given that Element has zero support for arrays, I think this is a very decent score.

Since most people are probably unfamiliar with this language, Element is a golfing language I created in 2012. You can see the most updated interpreter, written in Perl, here.

To make the explanation easier, I'll replace the newline with an `L`.

```
_'[1+2:'.2:`\ ."\L`]
_'                    input a number and put it onto the control stack
  [                ]  this is a FOR loop
   1+                 increment the number.  An empty stack is zero.
     2:               make a second copy of it
       '              put one copy on the control stack to save it
        .             append the other copy to the end of the string
         2:           make a second copy of the new string
           `          output one of them
            \ .       append a space to the other
               "      put the number from earlier pack onto the main stack
                \L`   output a newline, but the L should be an actual newline

```

# Answer
> 0 votes
# Python 2, 60 bytes

One byte less than current best in Python 2, so I've decided to post it.

```
def f(x):
 if x:f(x-1);print" ".join(map(str,range(1,x+1)))

```

Usage:

```
f(5)

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

```

# Answer
> 0 votes
Three slightly different approaches

# Ruby, 37 bytes

```
f=->n{n.times{|i|puts [*1..i+1]*" "}}

```

# Ruby, 38 bytes

```
f=->n{puts (1..n).map{|i|[*1..i]*" "}}

```

# Ruby, 40 bytes

```
f=->n{([*1..n+1]*" ").scan(/ /){puts$`}}

```

# Answer
> 0 votes
## UniBasic 50 Bytes

```
S='';INPUT N;FOR I=1 TO N;S:=I;CRT S;S:=' ';NEXT I

```

Ungolfed:

```
S=''
INPUT N
FOR I=1 TO N
  S:=I
  CRT S
  S:=' '
NEXT I

```

# Answer
> 0 votes
# q, 18 bytes

```
1+til each 1+til n

```

# Answer
> 0 votes
# MATLAB, 63

```
for m=1:input('');fprintf(['1' repmat(' %d',1,m-1) 10],2:m);end

```

Not the best, but because of the requirements on spaces, functions like `num2str` and `disp` can't be used as they produce too many.

Run the code and enter the number when prompted (~=STDIN). It will then print the number triangle.

# Answer
> 0 votes
# JavaScript, 77 Bytes

```
function(n){for(i=1;i<=n;i++){a='';for(j=1;j<=i;j++)a+=j+' ';console.log(a)}}

```

# Answer
> 0 votes
# 05AB1E, 3 bytes

```
LL»

```

Try it online.

**Explanation:**

```
L      # Create a list in the range [1, (implicit) input]
 L     # Map each integer `i` to a list in the range [1, `i`]
  »    # Join the list of lists by newlines,
       # which implicitly also joins the inner lists by a single space
       # (and output it implicitly)

```

# Answer
> 0 votes
# Rockstar, ~~97~~ 93 bytes

```
listen to N
X's 0
while N-X
build X up
O's 1
Y's 1
while X-Y
let Y be+1
let O be+" "+Y

say O

```

Try it (Code will need to be pasted in)

## Original, 97 bytes

```
listen to N
X's 0
while N-X
build X up
O's 1
cut O
while X-O
rock O+1 in O

join O with " "
say O

```

# Answer
> 0 votes
# Nibbles, 2 bytes (4 nibbles)

```
.,$,

```

```
.,$,        # full program
.,$,$       # with implicit arg added
.           # map over
 ,          # range from 1..
  $         # input
   ,        # getting the range from 1..
    $       # each number

```

Fortunately, Nibbles' default formatting for lists-of-lists is a happy match to the required output.

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


title: Find the sum of the divisors of N

text:
# Question
Title: Find the sum of the divisors of N
Write a program that displays on the screen the sum of the divisors of a number (1 ≤ N ≤ 100) entered by the user in the range of 1 to N.

This is OEIS A000203.

---

Examples:

**Input**: 7

```
7 / 1 = 7
7 / 7 = 1

7 + 1 = 8

```

**Output:** 8

---

**Input:** 15

```
15 / 1 = 15
15 / 3 = 5
15 / 5 = 3
15 / 15 = 1

15 + 5 + 3 + 1 = 24

```

**Output:** 24

---

**Input:** 20

```
20 / 1 = 20
20 / 2 = 10
20 / 4 = 5
20 / 5 = 4
20 / 10 = 2
20 / 20 = 1

20 + 10 + 5 + 4 + 2 + 1 = 42

```

**Output:** 42

---

**Input:** 1

```
1 / 1 = 1

```

**Output:** 1

---

**Input:** 5

```
5 / 1 = 5
5 / 5 = 1

5 + 1 = 6

```

**Output:** 6

# Answer
> 22 votes
# 05AB1E, 2 bytes

```
ÑO

```

Try it online!

### How?

```
Ñ    Divisors
 O   Sum

```

# Answer
> 7 votes
# x86-64 Machine Code, 23 bytes

```
89 F9 89 FE EB 0D 89 F8 99 F7 F1 85 D2 99 0F 44 D1 01 D6 E2 F1 96 C3

```

The above bytes of code define a function that accepts a single integer, N, and returns the sum of its multiples as a result.

The single parameter is passed in the `EDI` register, consistent with the System V AMD64 ABI (as used on \*nix-style systems). The result is returned in the `EAX` register, as with all x86 calling conventions.

The algorithm is a very straightforward one, similar to many of the other submissions in other languages. We loop N times, each time computing the modulo and adding that to our running total.

**Ungolfed assembly mnemonics:**

```
; unsigned SumOfMultiples(unsigned N  /* (EDI) */)
    mov     ecx, edi      ; make copy of input N, to be used as our loop counter
    mov     esi, edi      ; make copy of input N, to be used as our accumulator
    jmp     CheckEnd      ; jump directly to 'CheckEnd'
AddModulo:
    mov     eax, edi      ; make copy of input N, to be used as input to DIV instruction
    cdq                   ; short way of setting EDX to 0, based on EAX
    div     ecx           ; divide EDX:EAX by ECX, placing remainder in EDX
    test    edx, edx      ; test remainder, and set ZF if it is zero
    cdq                   ; again, set EDX to 0, without clobbering flags
    cmovz   edx, ecx      ; set EDX to ECX only if remainder was zero (EDX = ZF ? 0 : ECX)
    add     esi, edx      ; add EDX to accumulator
CheckEnd:
    loop    AddModulo     ; decrement loop counter (ECX), and keep looping if it != 0
    xchg    eax, esi      ; move result from accumulator (ESI) into EAX
    ret                   ; return, with result in EAX

```

**Try it online!**

It sure seems like there should be a way to make this shorter, but I can't see it. Computing modulo on x86 takes quite a bit of code, since you do it using the `DIV` (or `IDIV`) instruction, and both of those use fixed input registers (`EDX` and `EAX`), the values of which get clobbered (because they receive the results, the remainder and quotient, respectively).

The only real tricks here are pretty standard golfing ones:

* I've structured the code in a somewhat unusual way so that I can use the CISC-style `LOOP` instruction, which is basically just a combination of `DEC`+`JNZ` with the `ECX` register as the implicit operand.
* I'm using `XCHG` at the end instead of `MOV` because the former has a special 1-byte encoding when `EAX` is one of the operands.
* I use `CDQ` to zero out `EDX` in preparation for the division, even though for unsigned division you would ordinarily just zero it using a `XOR`. However, `XOR` is always 2 bytes, while `CDQ` is only 1 byte. I use `CDQ` again a second time inside of the loop to zero `EDX`, before the `CMOVZ` instruction. This works because I can be guaranteed that the quotient of the division (in `EAX`) is always unsigned, so a sign-extension into `EDX` will set `EDX` equal to 0.

# Answer
> 5 votes
# C (gcc), 45 bytes

```
i,s;f(n){for(s=i=n;--i;)s+=n%i?0:i;return s;}

```

Try it online!

# Answer
> 4 votes
## C, C++, C#, D, Java, ~~65~~ 62 bytes

```
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i>0?0:i;return s;}

```

This works in all theses 5 programming languages because of similarities.

### C, C++ and D optimization : ~~62~~ 60 bytes

In C++ and D, integers convert implicitly to booleans ( Zero =\> false, Not Zero =\> true ), so you don't need to have the `!=0`

```
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}

```

### D optimization : golfy template system, 55 bytes

```
T d(T)(T n){T s,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}

```

### C++ optimization by c and c-- : ~~53~~ 52 bytes

```
int f(int n,int i=0){return++i<n?f(n,i)+i*!(n%i):n;}

```

**Code to test** :

C :

```
printf("%d %d %d %d %d", d(7), d(15), d(20), d(1), d(5));

```

C++ :

```
std::cout << d(7) << ' ' << d(15) << ' ' << d(20) << ' ' << d(1) << ' ' << d(5);

```

C# :

```
class FindSum
{
    int d(int n) { int s = 0, i = 1; for (; i <= n; ++i) s += n % i > 0 ? 0 : i; return s; }

    static void Main(string[] args)
    {
        var f = new FindSum();
        Console.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
    }
}

```

D :

```
writeln(d(7));
writeln(d(15));
writeln(d(20));
writeln(d(1));
writeln(d(5));

```

Java :

```
public class FindSum {
    int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i>0?0:i;return s;}

    public static void main(String[] args) {
        FindSum f = new FindSum();
        System.out.println(String.format("%d, %d, %d, %d, %d", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
    }
}

```

# Answer
> 3 votes
# Mathematica, 14 bytes

```
Tr@Divisors@#&

```

or an answer by @Loki

# Mathematica, 17 bytes

```
DivisorSum[#,#&]&

```

# Answer
> 3 votes
# Japt, 3 bytes

```
â)x

```

Try it online!

# Answer
> 3 votes
# Shnap, ~~44~~ 43 bytes

-1 bye thanks to Mr. Xcoder (lol I was outgolfed in my own language)

```
 $n return:{s=0for d:range(n+1)if n%d<1s+=d}

```

This is a function (`$` starts a function in Shnap).

Try it online!

Explanation:

```
$ n                        //Start function with parameter n
    return: {              //Technically, we are returning a scope-block, which evaluates to the last statement run
        s = 0              //Our result
        for d : range(n+1) //For each value in the iterator range(n+1)
            if n % d < 1  // If n is divisible by d
                s += d     // Add d to the sum
                           // Since (s += d) returns (s + d), and a scope-block returns the last run statement, this will be the last statement and equal to our result
    }

```

---

# Noncompeting, 19 bytes

After many language updates, this can now be reduced to a measly 19 bytes:

```
$n=>sum(factors(n))

```

Try it online!

# Answer
> 3 votes
# Brachylog, 2 bytes

```
f+

```

Try it online!

### Explanation

```
f       Factors
 +      Sum

```

# Answer
> 3 votes
# Risky, 3 bytes

```
+/?+??

```

Try it online!

# Answer
> 2 votes
# Jelly, 2 bytes

```
Æs

```

Try it online!

Built-in that does exactly as wanted.

# Answer
> 2 votes
# , ~~31~~ 26 bytes

```
function(N)(x=1:N)%*%!N%%x

```

Try it online!

Returns a `1x1` matrix.

Computes `!N%%x` maps elements `d` of `1:N` by: `d->(1 if d divides N, 0 otherwise)`

Then `x%*%x!N%%x` is the matrix product of `1:N` which results in the sum of `x` where `!N%%x` is `1`. Neat! Technically a port of Luis Mendo's Octave answer but I only saw that after I thought of this.

# \+ numbers, 14 bytes

```
numbers::Sigma

```

Try it online!

# Answer
> 2 votes
# Javascript, ~~54~~ 44 bytes

```
n=>[...Array(x=n)].reduce(y=>y+!(n%x)*x--,0)

```

Saved 10 bytes thanks to Shaggy

### Try it online!

```
const f = n=>[...Array(x=n)].reduce(y=>y+!(n%x)*x--,0)

console.log(f(7))
console.log(f(15))
console.log(f(20))
console.log(f(1))
console.log(f(5))
```

# Answer
> 2 votes
# Python, 44 bytes

```
lambda k:sum(i*(k%i<1)for i in range(1,1+k))

```
* Thanks to Stephen, save 1 byte by removing whitespace.
* Thanks to Jonathan Frech, save another 1 byte by changing if to multiply.

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

```
sigma

```

Try it online!

# Answer
> 2 votes
# J, 23 bytes

```
[:+/](([:=&0]|[)#])1+i.

```

Try it online!

For J fans, there is a clever 13 byte solution: `>:@#.~/.~&.q:` but since it wasn't my invention I'm not posting it as my official answer.

My own solution simply filters 1..n, finding divisors, then sums them. The crux of it is the dyadic fork

```
](([:=&0]|[)#])

```

Note that in this context `]` is 1..n, and `[` is n itself. Hence `]|[` are the remainders when dividing each element of 1..n into n, and `=&0` tells you if they're equal to 0.

# Answer
> 2 votes
# Pyth, 6 bytes

```
s*M{yP

```

**Try it here!**

Pyth doesn't have a built-in for divisors, so I think this is reasonable.

# Explanation

```
s*M{yP    - Full program with implicit input.

     P    - The prime factors of the input.
    y     - The powerset of its prime factors.
   {      - Deduplicate.
 *M       - Map with multiplication.
s         - Sum.
          - Implicitly display the result.

```

Given `20`, for instance, this is what our program does after each instruction:

* `P`: `[2, 2, 5]`.
* `y`: `[[], [2], [2], [5], [2, 2], [2, 5], [2, 5], [2, 2, 5]]`.
* `{`: `[[], [2], [5], [2, 2], [2, 5], [2, 2, 5]]`.
* `*M`: `[1, 2, 5, 4, 10, 20]`.
* `s`: `42`.

# Answer
> 2 votes
# Java (OpenJDK 8), ~~53~~ 51 bytes

```
n->{int s=0,i=0;for(;i++<n;)s+=n%i<1?i:0;return s;}

```

Try it online!

# Answer
> 2 votes
# MATL, 6 bytes

```
t:\~fs

```

Try it online!

-4 bytes thanks to @LuisMendo

# 10 bytes

My previous solution using a loop

```
:"G@\~@*vs

```

Try it online!

# 3 bytes

Using built-in

```
Z\s

```

Try it online!

# Answer
> 2 votes
# Haskell, 30 bytes

```
f n=sum[i|i<-[1..n],n`mod`i<1]

```

Try it online!

# Answer
> 2 votes
# Brain-Flak, 96 bytes

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

```

Try it online!

## Explanation:

Now outdated by improvements.

The heart of the algorithm is this:

```
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})) turns |N, M...| into |N mod M, M...|
{((<{}{}>))} if the top of stack is not zero, replace it and the second with zero

```

That is a modification on mod that will give us `M` if it is a factor of `N` and `0` otherwise. Full code is below.

```
((({})<>) place input, N on both stacks
{ Loop to find factors
 <
  (([()]{})) Decrement and Duplicate; get next factor to check
  { if not zero
   (<>({})<>) Copy N from other stack
   ({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})){((<{}{}>))} Code explained above
  }
  {} drop the zero
 >
 {} add the factor
}) push the sum

```

# Answer
> 2 votes
# Excel VBA, 41 Bytes

Anonymous VBE immediate window function that takes input from `[A1]` and outputs to the VBE immediate window

```
For i=1To[A1]:s=s-i*([A1]mod i=0):Next:?s

```

# Excel, 41 Bytes

Worksheet formula that takes input from `[A1]` and outputs to the caller

Requires MS Excel Version 16.0 or later for access to `Let(...)` function

```
=LET(a,SEQUENCE(A1),SUM((MOD(A1,a)=0)*a))

```

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

```
sum(seq(Inot(fPart(Ans/I)),I,1,Ans

```

Takes input in `Ans`. Output is stored in `Ans` and displayed.

# Answer
> 2 votes
# Vyxal `s`, 1 byte

```
K

```

Try it Online!

`K∑` flagless. `K` just gets the divisors of a number.

# Answer
> 2 votes
# Husk, 2 bytes

```
ΣḊ

```

Try it online!

# Answer
> 2 votes
# Raku, ~~25~~ ~~23~~ 22 bytes

thanks ovs for 2 byte improvement
also JoKing for 1 byte improvement

```
{sum grep $_%%*,1..$_}

```

```
declare anonymous block ($_ implicitly declared)
filter (grep) numbers from 1 to $_ inclusive using the whatever variable (*) that are divisible by $_
get the sum of that list

```

Try it online!

# Answer
> 2 votes
# tinylisp, ~~74~~ 73 bytes

```
(load library
(d D(q((K N)(i K(a(i(mod N K)0 K)(D(s K 1)N))0
(q((N)(D N N

```

Try it online!

-1 byte thanks to DLosc.

And without `library` just for fun:

# tinylisp, ~~97~~ 90 bytes

```
(d D(q((N K)(i(l N K)N(D(s N K)K
(d F(q((K N)(i K(a(i(D N K)0 K)(F(s K 1)N))0
(q((N)(F N N

```

Try it online!

-7 bytes thanks to DLosc.

# Answer
> 1 votes
# JavaScript, 31 bytes

```
f=(n,i=n)=>i&&!(n%i)*i+f(n,i-1)

```

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

```
a=Cells(1,1)
x=1
While x<=a
If a Mod x = 0 Then b=b+x
x=x+1
Wend
MsgBox b

```

# Answer
> 1 votes
# Bash + GNU utilities, 36

```
bc<<<`seq -f"n=%g;a+=n*!$1%%n;" $1`a

```

Try it online.

---

# Pure Bash, 41

```
for((;++i<=$1;a+=$1%i?0:i))
{
:
}
echo $a

```

Try it online.

I first tried a fancy bash expansion answer, but it ended up being longer than the simple loop above:

```
echo $[$(eval echo +\\\(n={1..$1},$1%n?0:n\\\))]

```

# Answer
> 1 votes
# Python 2, 41 bytes

```
f=lambda n,i=1:i<=n and(n%i<1)*i+f(n,i+1)

```

Try it online!

# Answer
> 1 votes
# Add++, 9 bytes

```
D,f,@,dFs

```

Try it online!

I clearly got here too late. This defines a function that gets the factors, then sums them.

# Answer
> 1 votes
# Ohm v2, 2 bytes

Try it online!

This is pretty straight-forwad:

```
V   - Divisors.
 Σ  - Sum.

```

# Answer
> 1 votes
# Husk, 5 bytes

```
ṁΠuṖp

```

Try it online!

# How?

```
ṁΠuṖp  - Full program, implicit input.

     p  - Prime factors.
    Ṗ   - Powerset.
   u    - Remove duplicates.
ṁΠ     - Get the product of each list, sum and implicitly output.

```

Thanks to Zgarb for the suggestions in chat!

# Answer
> 1 votes
# Gaia, 2 bytes

Try it online!

Pretty straight-forward:

```
dΣ   - Full program.

d    - Divisors.
 Σ   - Sum.

```

# Answer
> 1 votes
# Neim, 2 bytes

```

```

Try it online!

# Answer
> 1 votes
# Octave, 20 bytes

```
@(n)~mod(n,t=1:n)*t'

```

**Try it online!**

# Answer
> 1 votes
# PowerShell, 36 bytes

```
param($a)1..$a|%{$j+=$_*!($a%$_)};$j

```

Try it online!

### Explanation

```
param($a)1..$a|%{$j+=$_*!($a%$_)};$j
param($a)                            # Takes input $a
         1..$a|%{               };   # For-loop from 1 up to $a
                          $a%$_      # Modulo, if this is zero we've hit a divisor
                        !(     )     # Take the Boolean-not of that. If a divisor, it's 1
                     $_*             # Multiply the current number by that Boolean
                                     # Only if it's a divisor will this be non-zero
                 $j+=                # Add it into our accumulator
                                  $j # Output our accumulator

```

# Answer
> 1 votes
# Axiom, 42 bytes

```
f(x:PI):PI==(x=1=>1;reduce(+,divisors(x)))

```

results

```
(19) -> [[i,f(i)] for i in [7,15,20,42,1,5] ]
   (19)  [[7,8],[15,24],[20,42],[42,96],[1,1],[5,6]]
                                          Type: List List PositiveInteger

```

# Answer
> 1 votes
# APL, 9 bytes

```
+/⍳×0=⍳|⊢

```

Try it online!

## How? (input **n**)

* `⍳|⊢`, `[n mod 1, ..., n mod n]`
* `0=`, `[0 == n mod 1, ... 0 == n mod n]`
* `⍳×`, `[1*(0 == n mod 1), ..., n*(0 == n mod n)]`
* `+/`, `sum([1*(0 == n mod 1), ..., n*(0 == n mod n)])`

# Answer
> 1 votes
# Rockstar, 96 bytes

```
listen to N
X's0
T's0
while N-X
let X be+1
let D be N/X
turn up D
let T be+D is N/X and X

say T

```

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

# Answer
> 1 votes
# GolfScript, 15 bytes

```
~.,{.3$\%!*+}*+

```

Try it online!

```
~                # Parses the input to integer
 .,              # Makes an array with numbers from 0 to (N-1)
   {.3$\%!*+}    # This block goes to the top of the stack without being executed
             *   # Folds
              +  # Adds the input and the result

```

What the block does:

```
    .            # Duplicates the number of the array
     3$          # Makes a copy of N
       \%!       # Tests if the number of the array is a divisor of N
          *      # Multiplies, resulting in the divisor if it was divisible or 0 if it wasn't
           +     # Adds to the acumulator

```

# Answer
> 1 votes
# x86-16 machine code, 18 bytes

```
00000000: 89c1 9988 0e09 0150 d40a 7502 02d4 58e2  .......P..u...X.
00000010: f2c3                                     ..

```

Listing:

```
89 C1           MOV  CX, AX                 ; input number as loop counter
99              CWD                         ; zero DX as running sum
            DIVLOOP:
88 0E 0109      MOV  BYTE PTR[AAM1+1], CL   ; move loop counter to divisor
50              PUSH AX                     ; save input number
            AAM1:
D4 0A           AAM                         ; ZF if (AL % CL == 0), AH = quotient
75 02           JNZ  END_LOOP               ; if not ZF, continue loop
02 D4           ADD  DL, AH                 ; otherwise add to running sum
            END_LOOP:
58              POP  AX                     ; restore input number
E2 F2           LOOP DIVLOOP                ; loop until CL == 0
C3              RET                         ; return to caller

```

Callable function, input `N` in `AX`, result in `DX`.

Inspired by @CodyGray's excellent answer, and the comment `"It sure seems like there should be a way to make this shorter"` I just had to try!

As Cody mentioned, Using `DIV`/`IDIV` is inconvenient because it clobbers two registers including the dividend. Another is that the `ZF` flag is set when the quotient is `0`, however in this case we're only interested in when the remainder is `0`. Enter `AAM`, a trusty and underrated byte-sized division/modulo instruction that can be golfy. Even though it does clobber the dividend just like `DIV`, it will set `ZF` when the remainder is `0` which is what we want here. It's downside is that the divisor is encoded in the instruction opcode, which can be modified at runtime at a cost of 4 bytes (in real mode at least).

# Answer
> 1 votes
# Python 3, 45 bytes

```
lambda n:sum(i for i in range(1,n+1)if n%i<1)

```

Try it online!

# Answer
> 1 votes
# Kotlin, 42 bytes

```
{var s=0;for(i in 1..it)if(it%i==0)s+=i;s}

```

Try it online!

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

```
{+/&~1!x%!1+x}

```

Try it online!

* `!1+x` generate sequence from `1..x`
* `x%` divide the input by each term in this range
* `&~1!` identify values in the range that evenly divide the input
* `+/` take (and implicitly return) their sum

# Answer
> 1 votes
# Factor \+ `math.primes.factors math.unicode`, 15 bytes

```
[ divisors Σ ]

```

Try it online!

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

```
+Sk

```

Try it online!

```
+Sk
 S  # Sum
  k # The divisors
+   # And add the input

```

# Answer
> 1 votes
# Prolog (SWI), ~~60~~ 56 bytes

*-4 bytes thanks to @Steffan*

```
N+X:-bagof(M,(between(1,N,M),N mod M<1),L),sumlist(L,X).

```

Try it online!

# Answer
> 1 votes
# Go, 62 bytes

```
func p(n int)(p int){i:=1
for;i<=n;i++{if n%i<1{p+=i}}
return}

```

Attempt This Online!

-2 bytes compared to my answer to Product of Divisors via use of Go's 0-initialization for variables.

# Answer
> 1 votes
# Arturo, ~~19~~ 16 bytes

```
$=>[∑factors&]

```

Try it

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

```
{+/t(*=(t:1+!x)!'x)}

```

Try it online!

I honestly didn't know how I manage to make a for-each that find the divisors, lol.

Explanations:

```
{+/t(*=(t:1+!x)!'x)}  Main function. x is input
    (           'x)   For x amount of times
               !      Modulo it with
       (    !x)       Range, create a list of [0..x-1]
          1+          + 1 to each number in list to turn it into [1..x]
        t:            Assign it to variable t
                      Now, we got the modulo results of each number from [1..x],
                      we now need to
      =               Group them into a dictionary
     *                And get the value of the first key
                      i.e. the occurence positions of the 0s
                      (Implicit at)
   t                  The variable t
 +/                   Sum

```

# Answer
> 1 votes
# Thunno, \\$ 2 \log\_{256}(96) \approx \\$ 1.65 bytes

```
fS

```

Attempt This Online!

```
f   # Factors
 S  # Sum

```

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

```
F

```

Attempt This Online!

Or, `FS` flagless.

# Answer
> 0 votes
# RProgN 2, 2 bytes

```
ƒ+

```

## Explained

```
ƒ+
ƒ   # Factorize
 +  # Sum

```

Trivial, but felt it needed to be posted.

Try it online!

# Answer
> 0 votes
# Perl 5, 35 + 1 (-p) = 36 bytes

```
$\+=($n%$_==0)&&$_ for 1..($n=$_)}{

```

Try it online!

# Answer
> 0 votes
# Recursiva, ~~20~~ 18 bytes

```
smBa++'%'Va'a:0!a'

```

Try it online!

# Explanation:

```
smBa++'%'Va'a:0!a' - Input to a; 20
s                    - sum up; 42
 m                   - map with; [1, 0, 3, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15]
  Ba                 - Range; [1,2..20]
    ++'%'Va'a:0!a'   - function, evaluates to 0 if param cannot divide a i.e. 20

```

# Answer
> 0 votes
# QBIC, 17 bytes

```
[:|~b%a|\p=p+a}?p

```

## Explanation

```
[:|      FOR a = 1; a <= b (read from cmd line); a++
~b%a|    IF b modulo a has a remainder THEN - empty block -
\p=p+a   ELSE add divisor 'a' to running total 'p'
}        END IF, NEXT
?p       PRINT p

```

# Answer
> 0 votes
# CJam, 16 bytes

```
ri:X{)_X\%!*}%:+

```

**Try it online!**

### Explanation

```
ri                 e# Read integer, n
  :X               e# Write to variable X
    {       }%     e# Map this block over the array [0 1 ... n-1]
     )             e# Increment current value. Will give 1, 2, ..., n
      _            e# Duplicate
       X           e# Push input
        \          e# Swap
         %         e# Modulus
          !        e# Negate
           *       e# Multiply
              :+   e# Sum of array. Implicitly display

```

# Answer
> 0 votes
## C#, 56 bytes

---

### Data

* **Input** `Int32` `i` A number
* **Output** `Int32` The sum of the divisors of the number

---

### Golfed

```
i=>{int s=0,d=1;for(;d<=i;d++)s+=i%d<1?i/d:0;return s;};

```

---

### Ungolfed

```
i => {
    int
        s = 0,
        d = 1;

    for( ; d <= i; d++ )
        s += i % d < 1 ? i / d : 0;

    return s;
};

```

---

### Ungolfed readable

```
// Takes an int
i => {
    // Initializes the sum 's' and divider 'd' vars
    int
        s = 0,
        d = 1;

    // Cycles each number lower than the the number 'i'
    for( ; d <= i; d++ )

        // Sums the result of the division between 'i' and 'd' if the modulus is 0
        s += i % d < 1 ? i / d : 0;

    // Returns the sum
    return s;
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace TestBench {
    public class Program {
        // Methods
        static void Main( string[] args ) {
            Func<Int32, Int32> f = i => {
                int s = 0, d = 1;

                for( ; d <= i; d++ )
                    s += i % d < 1 ? i / d : 0;

                return s;
            };

            List<Int32>
                testCases = new List<Int32>() {
                    7,
                    15,
                    20,
                    42,
                    1,
                    5,
                };

            foreach( Int32 testCase in testCases ) {
                Console.WriteLine( $" INPUT: {testCase}\nOUTPUT: {f( testCase )}" );
            }

            Console.ReadLine();
        }
    }
}

```

---

### Releases

* **v1.0** \- `56 bytes` \- Initial solution.

---

### Notes

* None

# Answer
> 0 votes
## Batch, 70 bytes

```
@set/ai=%2+1,s=%3+i*!(%1%%i)
@if not %i%==%1 %0 %1 %i% %s%
@echo %s%

```

Alternative solution, also 70 bytes:

```
@set s=0
@for /l %%i in (1,1,%1)do @set/as+=%%i*!(%1%%%%i)
@echo %s%

```

# Answer
> 0 votes
# MY, 4 bytes

```
ωḊΣ↵

```

Try it online!

## How?

It's really simple: `ω` is the argument,  is divisors, `Σ` is sum,  is output. I thought I already answered this challenge, for some reason.

# Answer
> 0 votes
# Ruby, 29 bytes

```
->x{(1..x).sum{|r|x%r>0?0:r}}

```

Try it online!

# Answer
> 0 votes
## Clojure, 53 bytes

```
#(apply +(for[i(range 1(inc %)):when(=(mod % i)0)]i))

```

# Answer
> 0 votes
# Casio-Basic, 42 bytes

```
sum(seq(piecewise(n/x=int(n/x),x,0),x,1,n

```

The `piecewise` acts as a shorter `If` statement. `seq` loops values of x from 1 to n, and the `piecewise` returns x if the number is a factor, otherwise it returns 0. `sum` adds the whole list together to output the total.

41 bytes for the function, +1 to add `n` in the parameters box.

# Answer
> 0 votes
# Ruby, 27 bytes

```
->x{(1..x).sum{1[x%_1]*_1}}

```

Attempt This Online!

Abuses Ruby's nth bit operator.

# Answer
> 0 votes
# MathGolf, 2 bytes

```
─Σ

```

One of many 2-bytes answers in a code-golf language.

Try it online.

**Explanation:**

```
─   # Get a list of divisors of the (implicit) input-integer
 Σ  # Sum them together
    # (after which the entire stack is output implicitly as result)

```

# Answer
> 0 votes
# cQuents, 3 bytes

```
Uz$

```

Try it online!

## Explanation

```
     implicit mode sequence - print nth term in sequence given input n
U    sum (                           )
 z         divisors (              )
  $                   current term

```

---
Tags: code-golf, sequence, integer, division, factoring
---