# Background:

A sequence of infinite naturals is a sequence that contains every natural number infinitely many times.

To clarify, every number must be printed multiple times!

# The Challenge:

Output a sequence of infinite naturals with the shortest code.

# Rules:

1. Each number must be separated by a (finite) amount of visible, whitespace or new line characters that aren't a digit.
2. The program cannot terminate (unless you somehow wrote all numbers).
3. Any way of writing such a sequence is acceptable.

# Examples:

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, 1, 2, 1, 2, 3, 1, 2, 3, 4...

Notice that we write all naturals from 1 to N for all N ∈ ℕ.

Feedback and edits to the question are welcome. Inspired by my Calculus exam.

• Welcome to the site! This is an interesting question, and a nice first attempt. In the future, we recommend using the Sandbox to get feedback before posting to main. There are a couple of clarifications needed here. It took me a few rereads to understand that each number has to appear multiple times, so I'd recommend rewording that to made it clearer. Also, I'd be surprised if this isn't a duplicate of an existing challenge, so don't be discouraged if this is closed as a duplicate (+1 if not however) Commented Nov 30, 2020 at 17:57
• Are nested lists and/or non-natural numbers permitted? Commented Nov 30, 2020 at 18:28
• @UnrelatedString nested lists yes, I will edit the post but non-natural numbers are not permitted. Commented Nov 30, 2020 at 18:30
• Is it OK if the output is in random order (as long as all numbers are printed infinitely often with probability 1)? Commented Nov 30, 2020 at 18:39
• Is it acceptable if floating-point limitations are ignored? For example, if $r$ is a uniformly distributed random float on $(0,1)$, can we assume $1/r$ can be arbitrarily large? (it can in theory, but not in practice due to realmin) Commented Nov 30, 2020 at 19:03

# Scratch 3.0, 13 20 blocks/121 70 bytes

As SB Syntax:

define(n)(i
say(i
((n)+<(i)=(n)>)((1)+((i)*<(i)<(n


This says each term in the sequence. A delay can be added so that the numbers don't rapidly fire.

I have never seen scratch so abused. You call the empty name function with empty parameters. My goodness. Whatever saves bytes!

-51 thanks to @att

Try it on Scratch

## Explained

The main idea behind this program is that each "run" of natural numbers is printed until the value being printed is equal to the highest number of that run.

The first two lines of the function are pretty straightforward...define a function with parameters n (the upper limit of the current run of numbers) and i (the current number for printing), then output the value of i.

Then, we get to the fun part - the function call. The expression n + (i = n) determines if we need to move onto the next n: if i hasn't reached the upper limit, the expression evaluates as n. Otherwise, the expression is n + 1, giving us the next upper limit.

The expression 1 + (i * (i < n)) determines the next value of i. To properly understand this, consider the two different results i < n can evaluate to: if i is equal to n (that is, we have reached the upper limit of the current run and we need to consequently restart at 1), this will result in (1 + (i * 0)), which will always equal 1. However, if i is less than n, the expression will equal (1 + (i * 1)) = (1 + i) , which just happens to be the next value to print. Because there is no checks to see if execution should be halted, this goes on forever.

• My favorite so far Commented Nov 30, 2020 at 21:35
• 74 bytes, but more blocks.
– att
Commented Dec 1, 2020 at 1:03
• 70
– att
Commented Dec 1, 2020 at 1:07
• How soon is soonish? Commented Jan 23, 2021 at 10:39
• @cairdcoinheringaahing soon enough Commented Jan 23, 2021 at 10:39

# Husk, 2 bytes

ḣN


Try it online!

First Husk answer! Also uses the sequence in the question

## How it works

ḣN - Main program
N - The infinite list [1, 2, 3, ...]
ḣ  - Prefixes; [[1], [1, 2], [1, 2, 3], ...]

• nice answer, gamer! Welcome to husk. Commented Dec 1, 2020 at 2:29
• This is 2 characters but 4 bytes: printf 'ḣN' |hd gives 00000000 e1 b8 a3 4e |...N| Commented Dec 3, 2020 at 18:08
• @AdamKatz If encoded as UTF8, then yes. However, Husk (along with a lot of other golfing languages, such as 05AB1E and Jelly) uses a custom codepage to encode it's programs. As bytes, this is DD 4E, but the code page is used to make it look nicer Commented Dec 3, 2020 at 18:10
• 😯 whoa, that's neat Commented Dec 3, 2020 at 18:13

# 05AB1E, 2 bytes

∞L


Try it online! The footer formats the output like the example from the post.

∞ pushes a list of all natural numbers, L takes the range [1 .. n] for each number.

# Python 2, 31 bytes

R=1,
while 1:print R;R+=len(R),


Try it online!

Thanks to @Danis for saving a byte here over R+=R[-1]+1,. This

Prints:

(1,)
(1, 1)
(1, 1, 2)
(1, 1, 2, 3)
(1, 1, 2, 3, 4)
(1, 1, 2, 3, 4, 5)
...


Accumulates a list of number from 1 to n (except 1 appears twice) each time appending the last element plus one.

32 bytes

R=[1]
for x in R:print R;R+=x+1,


Try it online!

# Python 2, 30 bytes (conjectured)

n=2
while 1:print~-2**n%n;n+=1


Try it online!

The sequence of $$\2^n \bmod n\$$ (A015910) is conjectured to take on all values $$\k \geq 0\$$ except $$\k=1\$$. I don't know if it's also conjectured that each value appears infinitely many times, but it seems consistent with known solutions for specific values.

We instead compute $$\(2^n-1) \bmod n\$$, which makes $$\0\$$ rather than $$\1\$$ be the only missing value (if the conjecture holds).

Looking at the output, you might think that $$\2\$$ is never output, but it in fact does appear first for $$\n=4700063497\$$ and for progressively higher values in A050259.

# Python 2, 33 bytes

R=[1]
for x in R:print x;R+=x+1,1


Try it online!

This is longer, but it's pretty nifty, printing the ABACABA sequence.

• you can write len(R) instead of R[-1]+1, but then at the beginning there will be two ones Commented Dec 1, 2020 at 7:55
• the conjecture is cool but integers 2, 4, 6, 8 seem to be missing (from my brief look)?! Commented Dec 3, 2020 at 2:11
• @roblogic See my comments on the post about 2. The other evens should also appear in the corresponding OEIS sequences.
– xnor
Commented Dec 3, 2020 at 2:15
• Side bar: Every once in a while I remember how mind-blowing it is that I can off the cuff verify your calculation for 𝑛=4700063497 in about 20 seconds on my laptop. What if Gauss had access to an iPad? :) Commented Dec 18, 2020 at 5:46

# R, 2625 24 bytes

-1 byte thanks to Dominic van Essen

repeat cat(rpois(9,9)+1)


Try it online!

Outputs a random infinite sequence of integers, drawn from the $$\Poisson(9)\$$ distribution (+1 to avoid outputting any 0s). They are output in batches of 9 at a time, for more "efficiency". Any positive value of the mean would work; using a mean of 9 maximizes the variance for 1-character numbers.

All numbers appear infinitely often in the sense that for any integer $$\k\$$, the expected number of occurences of $$\k\$$ in the first $$\n\$$ realizations goes to $$\\infty\$$ as $$\n\to\infty\$$:

$$E\left[\sum_{i=1}^n\mathbb{I}_{X_i=k}\right]\xrightarrow[n\to\infty]{}\infty.$$

The calls to cat mean that there integers within one batch of 9 are separated by spaces, but there is no separator between batches. The vast majority of 3- and 4-digit numbers in the output are due to this artefact, but there is a theoretical guarantee that such numbers (and larger numbers) will be output eventually, at least if we assume that the underlying random number generator is perfect.

For a larger variance, we can follow Giuseppe's suggestion for the same byte count:

repeat cat(1%/%runif(9))


Try it online!

This induces more 1s and more large numbers (including some very large numbers thanks to the cat artefact). Again, number of occurrences of any integer goes to infinity when the size of the output goes to infinity.

Two other R answers come out shorter, using deterministic methods: Giuseppe's and Dominic van Essen's

• I suppose the negative binomial / geometric distributions would work as well, though the parameters don't quite lend themselves to as short an answer. Commented Nov 30, 2020 at 19:06
• @AdamKatav They are just less likely Commented Nov 30, 2020 at 19:27
• @AdamKatav There will be if you wait long enough. For instance about 1 in 343 numbers is a 20. In the TIO output, a browser search reveals instances of 20, 21, 22, 23 and 24, and we would get higher numbers if more output were shown. Commented Nov 30, 2020 at 19:28
• There's also 1%/%runif(9) which should be a bit more evenly distributed, for the same byte count. I tried all the other built-in distributions in R. I do think that %/% will give some weird results but that's due to floating point precision issues, so it's nothing your answer doesn't already suffer from! Commented Nov 30, 2020 at 19:47
• Both can be 24 bytes using repeat  (without parentheses), but in the meantime I've found a different 23 byte answer... Commented Dec 1, 2020 at 8:45

# Haskell, 17 bytes

[[1..x]|x<-[1..]]


Try it online!

Since the challenge seems to allow non-flat output, we can simply generate a list of the lists [1],[1,2],[1,2,3,],..., as suggested by @AZTECCO.

l=1:do x<-l;[x+1,1]


Try it online!

A recursively-defined infinite flat list with the ABACABA sequence 1,2,1,3,1,2,1,4,... (A001511).

A same-length variant:

l=(:[1]).succ=<<0:l


Try it online!

20 bytes

l=do x<-[1..];[1..x]


Try it online!

Counting up 1,1,2,1,2,3,1,2,3,4,..., but as a flat list.

• Also [[1..x]|x<-[1..]] Commented Dec 1, 2020 at 2:06
• Interesting, I missed that the output doesn't have to flat.
– xnor
Commented Dec 1, 2020 at 2:11
• Worth mentioning Commented Dec 1, 2020 at 5:43
• The community concensus seems to be that [[1..x]|x<-[1..]] is a valid anonymous function, which wouldn't need the l=. And I don't see how l= makes this more valid.
– ovs
Commented Dec 1, 2020 at 8:42
• worth mentioning inits [1..] as well. Ofc inits requires an import so not a very good solution Commented Dec 6, 2020 at 17:30

# R, 21 bytes

(also near-simultaneously identified by Robin Ryder)

while(T<-T+1)cat(T:0)


Try it online!

Similar to the example sequence, but each sub-series is reversed, and the initial value in each subseries is represented with an initial zero (so, 03 for 3, for instance).

If you don't like the initial zeros, then look at the previous version using show (below), or at Giuseppe's answer.

# R, 23 22 bytes

Edit: -1 byte thanks to Robin Ryder

while(T<-T+1)show(1:T)


Try it online!

Outputs the sequence used in the example, plus an additional infinite number of copies of the number 1.
Each number is separated by either a space " " , a newline plus bracket, "\n[", or a bracket plus space "[ ".

2-bytes golfier (at time of posting, at least...) than the other two R answers...

• 21 bytes, but some integers are prefixed with a 0; I don't know whether that is acceptable. Commented Dec 1, 2020 at 9:06
• @RobinRyder - Yes, I got that too, but I'm waiting for the OP to clarify if this is Ok... Commented Dec 1, 2020 at 9:07
• If the initial 0 is ruled unacceptable, this works for 22 bytes; a rare use for show! Commented Dec 1, 2020 at 9:17
• @RobinRyder - Super! Thanks! I don't think I've ever used show before... Commented Dec 1, 2020 at 9:20
• can we replace show with cat? Or am I missing something?
– JDL
Commented Dec 1, 2020 at 11:18

# Bash + GNU Coreutils, 20

seq -fseq\ %g inf|sh


Try it online! - Times out after 60 seconds.

# Bash, 20 bytes

seq inf|xargs -l seq


Try it online!

# sed 4.2.2, 20

:;s/(1*).*/1\1 &/p;b


Try it online!

Output is in unary, as per this meta consensus.

# Befunge, 5 bytes

>1+?.


Try it online!

At each output, there is a 50% chance the current number will be printed and reset to 1, and a 50% chance that 2 will be printed and the current number will increase by some random odd number (following an exponential distribution). This can happen multiple times, so odd numbers can be outputted as well.

Every natural number has a nonzero probability of occurring, so it will eventually be printed infinitely many times.

### Explanation

>1+?.
>      # Go east.
1+    # Initialize a counter to 1.
?   # Go in a random direction.
# If the instruction pointer goes west:
+    # Add the top two stack elements together.
# If there is a 2 on top, this adds it to the counter.
# If not, this does nothing.
1     # Create a new 1 on the top of the stack.
>      # Go east.
1+    # Add 1 to get 2, which remains on top of the counter.
?   # Repeat.

?   # If the IP goes east:
.  # Print and delete the top of the stack.
>      # Go east.
1+    # Add 1.
# If there was a 2 that was printed and the counter remains, the 1 gets added to it.
# If the counter was printed instead, this creates a new 1.
?   # Repeat.

?   # If the IP goes north or south, it wraps around to the ? instruction and repeats.


# Befunge-98, 14 bytes

]:.1-:0j
]:+!


Try it online!

A determinstic solution, printing each range from 1 to n in descending order.

### Explanation

]           # Turn right (to the south) and go to the second line.

]:+!
]           # Turn right again (to the west).
!        # Take the logical NOT of the secondary counter (which is now 0) to get 1.
+         # Add the 1 to the main counter.
:          # Duplicate the main counter to form a secondary counter.
]           # Turn right (to the north) and go to the first line.

]:.1-:0j
]           # Turn right (to the east).
:          # Duplicate the secondary counter.
.         # Print and delete the duplicate.
1-       # Subtract 1 from the secondary counter.
0     # Is the secondary counter greater than 0?
j    # If so, jump over the ] instruction and repeat the first line.
]           # If not, turn right (to the south) and go to the second line.


# convey, 27 bytes

   >v
1","@"}
^+^<#-1
1+<<<


Try it online!

This counts down from successive numbers.

# Jelly, 4 bytes

‘RṄß


Try it online!

I think this outputs all numbers an infinite number of times, but because it's a different output format, I'm not 100% sure

## How it works

‘RṄß - Main link. Left argument is initially n = 0
‘    - Increment
R   - Range
Ṅ  - Print
ß - Recursively run the main link


For n = 0, ‘RṄ outputs [1]. We then recurse, using n = [1]. ‘RṄ then outputs [[1, 2]], and we recurse again, using n = [[1, 2]], which outputs [[[1, 2], [1, 2, 3]]] etc.

• That was very quick (5 min) Commented Nov 30, 2020 at 18:03
• @AdamKatav We have a lot of practice of finding quick answers :P Commented Nov 30, 2020 at 18:04

# Octave, 29 28 bytes

do disp(fix(1/rand)) until 0


Try it online!

This outputs a sequence $$\(x_k)\$$ of independent, identically distributed random natural numbers. Each value $$\x_k\$$ is obtained as $$\1/r\$$ rounded towards zero, where $$\r\$$ has a uniform distribution on the interval $$\(0,1)\$$.

For a given index $$\k\$$, and for any $$\n \in \mathbb N\$$, there is a nonzero probability that $$\x_k=n\$$ (ignoring floating-point inaccuracies). Therefore, with probability $$\1\$$ every $$\n\$$ appears infinitely often in the sequence $$\(x_k)\$$.

• "identically distributed random natural numbers", this is impossible, you can't have a uniform distribution over an infinite set. Commented Dec 2, 2020 at 13:16
• @PedroA Who said uniform? :-) The distribution has the approximate form $1/x^2$ (which results from dividing $1$ by a uniform number on $(0,1)$), and thus larger numbers are less likely Commented Dec 2, 2020 at 18:02

# R, 25 21 bytes

repeat T=print(T:0+1)


Try it online!

Prints 2..1, 3..1, 4..1 and so forth.

Thanks to Robin Ryder for -4 bytes.

This works because print invisibly returns its first argument.

• Commented Dec 1, 2020 at 8:40
• (although yours would be 24 bytes using repeat )... Commented Dec 1, 2020 at 8:47
• 21 bytes Commented Dec 1, 2020 at 8:59
• @RobinRyder nice, thanks! I couldn't get it to work using 0:T but didn't think of reversing it! Commented Dec 1, 2020 at 15:07

# C (gcc), 43 bytes

i;main(j){for(;;)printf("%d ",j=--j?:++i);}


Try it online!

# JavaScript (V8), 26 bytes

for(a=b='';;)write(a+=--b)


Try it online!

Character - used as a separator and the output starts with it, so I'm not really sure if this is acceptable.

• While it is a great answer, I don't know if it valid. Quoting the first rule: "Each number must be separated by a (finite) amount of visible, whitespace or new line characters that aren't a digit.". The dash/minus symbol isn't a whitespace or a newline. And certainly seems to be part of the number, but isn't a digit. I think that more clarification is needed, as this is a possible game changing detail. This means that anyone could just do their loops in reverse and get some savings, without needing the whitespace. TL;DR: may be invalid, O.P. needs to clarify better the rules. Commented Dec 2, 2020 at 12:03
• @IsmaelMiguel - "visible, whitespace or new line characters". The "-" character is visible, so it seems Ok to me... Commented Dec 3, 2020 at 17:58
• @DominicvanEssen My advice stands. Commented Dec 3, 2020 at 21:44

# Wolfram Language (Mathematica), 25 bytes

Do[Print@n,{m,∞},{n,m}]


Try it online!

-1 byte @att

• 25 bytes
– att
Commented Dec 24, 2020 at 19:00
• 24
– att
Commented Dec 26, 2020 at 6:58

# convey, 17 15 bytes

-2 thanks to Jo King!

>1\/v
:+<.+}
11


Try it online!

Previous version that used a 0-stream and incremented its indices by 1. Jo's variation uses a 1-stream that adds itself to its indices, thus shortening the last row.

Starting with the top left 0, we push it to the left. \ will push its length 1 downward, it will get incremented +1 and then length + 1 new 0s will be let through. So we generate 0, 0 0, 0 0 0, …

Those list get then dumped in a sink ] while their indices \. get incremented +1 and written to the output }: 1, 1 2, 1 2 3, …

• 15 bytes. I also attempted this on my own and ended up at 19 bytes through a slightly stranger method
– Jo King
Commented Jan 22, 2021 at 9:01
• @JoKing Thanks, that's a clever golf! Your other version is much more fun. I tried to golf it, but only got it down to 18b with !.
– xash
Commented Jan 22, 2021 at 13:53

# Regenerate-a, 14 bytes

(${$1+1} !1 )+


Attempt This Online!

The only choice for the regex to make here is how many times to repeat the (...)+ loop. The first iteration will always print 1 , because the first alternative can't match, as $1 hasn't been defined yet. On subsequent iterations, ${$1+1} does math on $1, treating its contents as a number. It ignores the trailing space, and adds 1 to it. This then becomes the new value for $1, etc. The ! short-circuiting alternation prevents the second alternative, i.e. 1 , from being taken once it becomes possible for the first alternative, ${1+1} , to match. • Of interest: using | instead of ! gives different output, but I think it still fits the challenge criteria. Commented Jul 5, 2022 at 18:56 ## Arm Thumb (with libc calls), 34 bytes Raw machine code f7ff fffe is for libc calls which haven't been linked yet. Needs to be loaded at an address that is not a multiple of 4, due to alignment requirements. Yes, it is counterintuitive, but it will make sense later. 2400 a707 3401 2501 0038 0029 f7ff fffe 3501 42a5 d9f8 200a f7ff fffe e7f2 7525 0020  Uncommented Assembly  .thumb .globl main .thumb_func main: movs r4, #0 adr r7, str .Lloop1: adds r4, #1 movs r5, #1 .Lloop2: movs r0, r7 movs r1, r5 bl printf adds r5, #1 cmp r5, r4 bls .Lloop2 .Lloop2_end: movs r0, #'\n' bl putchar b .Lloop1 str: .asciz "%u "  ### Explanation Equivalent C code: #include <stdio.h> #include <stdint.h> int main(void) { uint32_t N = 0; for (;;) { ++N; for (uint32_t num = 1; num <= N; num++) { printf("%u ", num); } putchar('\n'); } // Unreachable }  Since we are never returning from main, I say, "to hell with calling convention" and just overwrite the callee-saved registers with our local variables. They won't know the difference. 😈 Specifically, I want r4 to be N (it is incremented before using), and r7 to be our printf string. Unfortunately, we have an odd number of instructions, and adr can only load addresses that are 4 byte aligned, so we need to make main not be 4-byte aligned so the string is 4-byte aligned. main: movs r4, #0 adr r7, str  Begin printing the natural numbers. Increment N and start counting ℕ in r5. .Lloop1: adds r4, #1 movs r5, #1  printf("%u ", ℕ) .Lloop2: movs r0, r7 movs r1, r5 bl printf  Increment ℕ and loop while it is less than or equal to N.  adds r5, #1 cmp r5, r4 bls .Lloop2  After the second loop: putchar('\n') .Lloop2_end: movs r0, #'\n' bl putchar  Jump back to the outer loop to increment N.  b .Lloop1  The printf string. This must be 4-byte aligned for adr, which we do with how we load main. str: .asciz "%u "  # Brachylog, 4 bytes ⟦₁ẉ⊥  Try it online!  ẉ Print with a newline ⟦₁ the range from 1 to something, ⊥ then try again.  # J, 13 bytes :@,~[echo@#\


Try it online!

Outputs 1, 1 2, 1 2 3 4, 1 2 3 4 5 6 7 8, etc, with every number on its own line.

• echo@#\ Output the prefix lengths of the current list, ie, 1..n where n is the current list length. This is done as a side effect.
• $:@,~ Append the list to itself ,~ and call the function recursively $:@.

# Rust, 54 bytes

(2..).for_each(|x|(1..x).for_each(|y|print!("{} ",y)))


Try it online

• Welcome to the site, nice first answer! Commented Dec 1, 2020 at 0:33

# Ruby, 17 bytes

loop{p *1..\$.+=1}


Try it online!

# Charcoal, 8 bytes

Ｗ¹«Ｉ⊕ⅉＤ⸿


Try it online! Link is to verbose version of code. Works by repeatedly printing the next number to the canvas and then dumping the entire canvas.

2 bytes for a version that prints the $$\ n \$$th term of a sequence:

ＩΣ


Try it online! Explanation: Simply prints the digital sum of the input. Given any natural number $$\ n \$$, all the values of the form $$\ \frac { 10 ^ n - 1 } 9 10 ^ m \$$ have a digital sum of $$\ n \$$ for every $$\ m \$$, thus each natural number appears infinitely often.

# JavaScript (V8), 29 bytes

for(n=k=1;;)print(n=--n||k++)


Try it online!

# Factor, 32 bytes

1 [ dup bit-count . 1 + t ] loop


Try it online!

Loops over the positive integers and prints their bit count (the number of 1 bits, a.k.a. popcount) forever. Outputting nth term would be simply 9-bytes bit-count. (I checked that the function works with bigints.)

Uses the same logic as Neil's Charcoal answer that there are infinitely many numbers whose digit sum equals n, except that this one uses bits instead. More precisely, for any positive integer n, $$\2^m(2^n-1)\$$ for any non-negative integer m has exactly n bits on, so the sequence contains infinitely many n's for any n.

• My first idea was in fact bitcount but I then realised the same idea worked in base 10 anyway, which was trivial in Charcoal.
– Neil
Commented Dec 1, 2020 at 11:46

# JavaScript (Browser), 40 bytes

f=(x=1)=>setInterval(_=>alert(x,f(x+1)))


Not very competitive answer :(

# C (gcc), 52 49 44 bytes

Saved 5 bytes thanks to AZTECCO!!!

f(i,j){for(j=1;printf("%d ",j--);)j=j?:++i;}


Try it online!

• Why are you guaranteed to get i=1 when this is compiled? I see that it occurs reliably on tio, but I'm not sure why. Commented Nov 30, 2020 at 22:58
• 44 Commented Dec 1, 2020 at 2:04
• @AZTECCO Nice one - thanks! :D Commented Dec 1, 2020 at 7:05
• @bisen2 It doesn't matter what i is initialised to, all the positive (nothing will be output until i is greater than 0) numbers get output infinite number of times anyway. It just so happens that i initialised to 0` at the onset. Note: the answer has been changed. Commented Dec 1, 2020 at 7:08