49
\$\begingroup\$

Write a program or function which will provably print all integers exactly once given infinite time and memory.

Possible outputs could be:

0, 1, -1, 2, -2, 3, -3, 4, -4, …

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, …

This is not a valid output, as this would never enumerate negative numbers:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

  • The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses).

  • Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language.

  • Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language.

  • The separator must not change at any point.

  • The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. is as valid as just ,).

  • Any supported integer must eventually be printed after a finite amount of time.

Scoring

This is , so the shortest answer in bytes wins

Leaderboard

var QUESTION_ID=93441,OVERRIDE_USER=41723;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
  • 3
    \$\begingroup\$ If our language supports infinite lists, can we output the list from a function rather than printing? (Calling print on such a list would print its elements one at a time forever.) \$\endgroup\$ – xnor Sep 16 '16 at 8:57
  • 6
    \$\begingroup\$ I feel like the requirement on arbitrary-size integers does nothing but discourage languages without such integers from participating. They either have to have an import they can use or solve a totally different challenge from everyone else. \$\endgroup\$ – xnor Sep 16 '16 at 9:10
  • 2
    \$\begingroup\$ @xnor Changed, though that kinds of ruins the very name of the challenge. \$\endgroup\$ – Fatalize Sep 16 '16 at 9:14
  • 5
    \$\begingroup\$ @xnor, languages with arbitrary precision integers still have to solve a different problem from everyone else, so all that that change has accomplished is to make this problem boringly trivial in a lot of languages. \$\endgroup\$ – Peter Taylor Sep 16 '16 at 9:54
  • 2
    \$\begingroup\$ @PeterTaylor Yeah, this is unfortunate. The wrapping solutions don't feel to me like they are printing any negatives, but I don't see a way to firmly specify the difference when it's a matter of representation. \$\endgroup\$ – xnor Sep 16 '16 at 9:58

123 Answers 123

1
\$\begingroup\$

Python 3, 44 bytes

i=0;print(i)
while 1:i+=1;print(i);print(-i)

Try it online!

\$\endgroup\$
0
\$\begingroup\$

MATLAB 65 bytes

My earlier post was faulty because the loop does not stop. A better try is this:

a=intmin('int64');(a:-a)'

but while this will work for the smaller int8 type it will not for int64 as the maximum array size will (of course) be exceeded. Note that transposing the vector prevents the console output from being interrupted by 'columns m to n' messages.

Another funny with MATLAB is that integers do NOT roll over, thus intmax('int64') + 1 == intmax('int64') not intmin('int64') as I expected. Also, MATLAB does not have a 'do' loop, So the best I can think of is this:

a=intmin('int64');b=-a;while(1) a, if a==b break, end; a=a+1; end

an then only if we allow the 'any separator' to allow this:

a =
   -9223372036854775808
a =
   -9223372036854775807
...
a =
    9223372036854775806
a =
    9223372036854775807 

There must be a better way!

\$\endgroup\$
0
\$\begingroup\$

C, 64 Bytes

f(n){printf(",%d",n);n>0?f(-n),f(++n):0;}main(){f(printf("0"));}

A full program that terminates after printing all the integers it can represent.

Output

0,1,-1,2,-2,3,-3,4,-4,5,-5,6,-6,7,-7,8,-8,9,-9,10,...
\$\endgroup\$
0
\$\begingroup\$

Oracle SQL 11.2, 77 73 72 68 bytes

SELECT CEIL((LEVEL-1)/2)*(MOD(LEVEL,2)*2-1)FROM DUAL CONNECT BY 1=1;
\$\endgroup\$
0
\$\begingroup\$

Non-wrapping Brain****, 9 bytes

Thanks to Scepheo for saving one byte!

+[.+<.->] 
\$\endgroup\$
  • 1
    \$\begingroup\$ Duplicate answer. (the first part anyway) \$\endgroup\$ – Martin Ender Sep 16 '16 at 13:39
  • \$\begingroup\$ Non-wrapping can be shorter by printing before decrementing: +[.+>.-<] \$\endgroup\$ – Scepheo Sep 16 '16 at 13:47
0
\$\begingroup\$

Bash, 33 55 bytes

for((;;)){ echo -n $[-i++],$i,;((i==LLONG_MAX))&&exit;}

Unfortunately bash won't give an integer overflow error when $i exceeds the maximum size of the type used to store it. Therefore, I updated the code to include a termination criteria, that requires $LLONG_MAX to be defined in the environment or passed on the command line.

Run example: on my system bash uses signed 64-bit integers

LLONG_MAX=$[2**63-1] ./all_integers.sh

The following code is a 32 byte version (1 less) of my original post, that assumed undefined printing behavior after the integer overflow.

for((;;)){ echo -n $[-i++],$i,;}
\$\endgroup\$
0
\$\begingroup\$

C, 51 50 bytes

void f(){long i=0;for(;;)printf("%d %d ",i++,-i);}

I could save a byte by doing int instead of long, but since this can go longer than int without wrapping I'm leaving it.

Output:

0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 ...
\$\endgroup\$
  • \$\begingroup\$ This program will run forever, shouldn't it terminate after printing all the "longs"? P.S. you can save a byte using for(;;) in place of while(1) \$\endgroup\$ – cleblanc Sep 16 '16 at 17:30
  • \$\begingroup\$ A lot of the other answers here run forever, so I just went with it. That way, you can #define long into arbitrarily large types. Good tip on saving a byte though. \$\endgroup\$ – Cody Sep 16 '16 at 18:07
  • \$\begingroup\$ It's pointless to use long with a %d conversion (instead of %ld). On x86-64 with 64-bit long, printf it will only look at the low 32 bits of its args. I can't think of a plausible way for any normal calling convention on any ISA where %d would print a number outside the range of int; most calling conventions require functions to ignore garbage in high bits. You could save a ; by putting the variable declaration inside the for(). i.e. for(int i=0;;)printf.... Especially since you didn't omit the return-type or anything, so this is valid C99. \$\endgroup\$ – Peter Cordes Sep 16 '17 at 7:35
0
\$\begingroup\$

C++ with Boost, 143 bytes

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>
boost::multiprecision::cpp_int i;main(){while(++i)std::cout<<1-i<<','<<i<<',';}

Not very short, but it does use an arbitrary-precision type. To test that, I tried replacing ++i with i=2*i+1, and very soon there were numbers several hundred digits long being printed correctly. This should work until the number takes up all your stack memory.

\$\endgroup\$
  • \$\begingroup\$ Suggest turning the while loop into a for loop, replacing ',' with 44 and deleting the space after #include. \$\endgroup\$ – ceilingcat Nov 10 '16 at 1:38
0
\$\begingroup\$

Swift 3 (34 bytes)

(Int.min...Int.max).map{print($0)}

Really, we should be able to get this down to 30 bytes like so:

(Int.min...Int.max).map(print)

But the compiler doesn't allow this yet.

\$\endgroup\$
  • 1
    \$\begingroup\$ 30 bytes: print(Array(Int.min...(.max))) \$\endgroup\$ – Tamás Sengel Mar 29 '18 at 20:55
0
\$\begingroup\$

Actually, 7 bytes

01W;±@u

This solution requires infinite time to actually print anything. Finite memory will cause an out of memory error and premature printing. No TIO link for obvious reasons.

Explanation:

01W;±@u
0        push 0
 1       push 1
  W      infinite loop:
   ;       duplicate
    ±      unary negate
     @     swap with positive
      u    increment

This solution works for 8 bytes, prints a finite amount of numbers in a finite amount of time, and uses significantly less memory (the memory used doesn't start growing until after INT_MAX is printed, at which point Python seamlessly transitions to arbitrary-precision integers).

0■~W■±■~

Try it online! (only prints up to around 9292 due to timeout).

Explanation:

0■~W■±■~
0         push 0
 ■        print entire stack without popping (just the 0)
  ~       bitwise negate (~n is equivalent to -n-1)
   W      infinite loop:
    ■       print stack without popping
     ±      unary negate
      ■     print without pop
       ~    bitwise negate
\$\endgroup\$
  • \$\begingroup\$ This solution requires infinite time to actually print anything contradicts Any supported integer must eventually be printed after a finite amount of time \$\endgroup\$ – Fatalize Sep 17 '16 at 13:01
  • \$\begingroup\$ @Fatalize Integers will be printed after a finite amount of time, if there's a finite amount of memory available. \$\endgroup\$ – Mego Sep 17 '16 at 17:59
  • \$\begingroup\$ and they will never get printed in a finite amount of time with an infinite amount of memory, so this answer is invalid \$\endgroup\$ – Fatalize Sep 17 '16 at 18:13
  • \$\begingroup\$ @Fatalize Then please clarify that in the challenge body. \$\endgroup\$ – Mego Sep 17 '16 at 20:46
0
\$\begingroup\$

k (20 bytes)

The function between curly braces is repeatedly iterated on it's result, starting at zero, until the result converges at 0W (k infinity).

{-1@'$?-1 1*x;x+1}/0

The function prints the argument and its negation and then returns incremented argument.

\$\endgroup\$
0
\$\begingroup\$

C# function 53 bytes

int j;void X(){for(;;)Console.Write($"{j++},-{j},");}

Explanation:

Create a variable "j" in class scope. This will default to have a value of zero. Write and increment value and then write the negative of that value. This will output "0,-1," on the first loop and "1,-2," on the 2nd loop.

\$\endgroup\$
0
\$\begingroup\$

Python, 40 bytes

p=print
p(0)
i=1
while 1:p(i);p(-i);i+=1
\$\endgroup\$
  • \$\begingroup\$ You need to remove the p(0) line, or else 0 will be printed 3 times. \$\endgroup\$ – Mego Sep 26 '16 at 6:40
0
\$\begingroup\$

C++, 84 Bytes

#include <iostream>
int main(){for(int i=0;;)std::cout<<i++<<','<<-i<<',';return 0;}

Edit: thanks for the debugging, commenters

\$\endgroup\$
  • \$\begingroup\$ Welcome to PPCG! All answers need to be full programs or functions and the relevant includes/namespaces need to be counted as well. If you make your submission a full program, it should compile in any existing compiler as is, and if it's a function it should be possible to drop it into any program and use and compile it without any other additional code. \$\endgroup\$ – Martin Ender Sep 17 '16 at 15:53
  • \$\begingroup\$ That loop doesn't print a delimiter between the numbers. \$\endgroup\$ – celtschk Oct 13 '16 at 23:08
0
\$\begingroup\$

QBIC, 14 bytes

{?1-q ?q q=q+1

qis 1 by default in QBIC, so this prints (1-1=) 0, 1, -1, 2, -2... separated by line breaks.

\$\endgroup\$
0
\$\begingroup\$

Straw, 26 bytes

~(~$:>(,-)>:>(,)>#0+~:&):&

Try it online!

~(~$:>(,-)>:>(,)>#0+~:&):&
~ ~                 ~      Swap between the two stacks
 (                     )   Push a string literal
   $                       Unary -> decimal
    :      :         :     Duplicate
     >    > >   >          Output
      (,-)   (,)           String literal
                 #         Decimal -> unary
                  0        Push the character '0'
                   +       Concatenate
                      &  & Evaluate

It prints -0 too, not sure if it's allowed though

\$\endgroup\$
0
\$\begingroup\$

Pushy, 7 bytes

0[~#|h#

Try it online! (will eventually cut the output)

Explanation:

0     \ Push 0 as the starting counter
[     \ Infinitely:
 ~#   \   Negate counter (and print)
 |h   \   Push abs(counter)+1
 #    \   Print counter

This prints in the pattern 0 1 -1 2 -2 3 -3..., separated by newlines.

Pushy's reference implementation is in Python, which uses arbitrarily sized integers, and so there won't be any overflow if you run this for a long time. However, the integer would eventually get too large and cause a MemoryError.

\$\endgroup\$
0
\$\begingroup\$

CJam, 10 bytes

0{_n~_nz}h

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Triangular, 21 bytes

()ip.%@,|<.>A@\/A|%p<

(Does not work on the TIO version yet.) Formats into this triangle:

     (
    ) i
   p . %
  @ , | <
 . > A @ \
/ A | % p <

This got really messy once I realized there had to be delimiters between the numbers.

The directionals (<,>\/) poke the IP around to get this code executed:

(i%|A@p%|A@p)

How it works:

  • ( opens a loop.
  • i increments the top of stack.
  • % prints the top of stack as an integer.
  • | negates the top of stack.
  • A pushes 10 to the stack.
  • @ prints the top of stack as ASCII \n.
  • p pops the 10. Now the top of stack is the negated value.
  • % prints the top of stack (negated value).
  • | un-negates the top of stack.
  • A pushes 10 to the stack again.
  • @ prints as ASCII \n.
  • p pops the top of stack.
  • ) unconditionally jumps back to the loop.
\$\endgroup\$
0
\$\begingroup\$

Aceto, 9 bytes

dpnd~pnIO
d duplicates the top val
p prints it
n does a newline
~ negates  the top val
I Increments the top val
O returns to the beginning of the program

Try it online!

\$\endgroup\$
0
\$\begingroup\$

uBASIC, 24 bytes

An anonymous answer that takes no input and outputs to the console.

0?0
1i=i+1:?i,0-i:GoTo1:

Try it online! (and yes, the terminal : is necessary)

\$\endgroup\$
0
\$\begingroup\$

MY-BASIC, 38 bytes

Print 0;
While 1
i=i+1
Print-i;i;
Wend

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Yabasic, 22 bytes

An anonymous answer that takes no input and outputs all integers to the console.

?0
Do
i=i+1
?-i,i
Loop

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Visual Basic .NET (Mono), 95 bytes

A declared subroutine that takes no input and outputs to the console.

Module M
Sub Main
Dim i
Do
Console.WriteLine(-i &IIf(i," "&i,""))
i=i+1
Loop
End Sub
End Module

Try it online!

\$\endgroup\$
0
\$\begingroup\$

F#, 69 bytes

let f=
 let mutable i=0m
 while 1>0 do
  printf"%O,-%O,"i i
  i<-i+1m

It's pretty straight forward. The 0m sets i as 0, but of type decimal. Since we're allowed to print 0, -0 I'm doing that. i gets incremented with every iteration of the loop, and the value is printed out.

I my initial idea would have been 70 bytes but (like most of my initial ideas) it would never have worked:

let g=Seq.iter(fun x->printfn"%O,-%O"x x)[0m..System.Decimal.MaxValue]

In this one [0m..System.Decimal.MaxValue] creates an array starting at 0, adding 1 each time and going all the way to the maximum decimal value. (Another example would be the expression [1..10] creates an array with {1,2,3,4,5,6,7,8,9,10}).

Seq.iter would then apply the function for printing to that array.

The problem with this is that the array must be constructed before iterating through it. So for all integers, with infinite memory the array could be constructed - but it would also take an infinite amount of time, so nothing would ever be printed out!

\$\endgroup\$
0
\$\begingroup\$

Javascript, 96 bytes

f=n=>f([].concat(...n.map(i=>alert(+i?i+' -'+i:i)||+i?y.map(o=>i+o):[])));f(y=[...`0123456789`])

Alerts all integers in the sequence (0, 1, -1, 2, -2, ...), using strings to go beyond JS's usual max safe integer 9007199254740991. This is equivalent to the "Infinite version" in Arnauld's earlier answer.

\$\endgroup\$
0
\$\begingroup\$

Scala, 112 bytes

val x=Int.MaxValue
val y=Int.MinValue
print(0)
for(a <-1 until x) print(","+a + "," + a * -1)
print(","+x+","+y)

Try it online!

Testable Running Program with limits [-10,10]

Scala, 143 bytes

object ListNumbers extends App {
  val x = 10
  val y = -10
  print(0)
  for(a <- 1 until x) print(","+a + "," + a * -1)
  print(","+x+","+y)
}

Try it online!

Using Java 8 Streams just for fun, it generates a lazy populated string

types declarations can be omitted but I included for "documentation"

Scala, 253 bytes

val zero :Stream[String] = Stream("0")
val positive :Stream[Int]= Stream.from(1)
val negative :Stream[Int]= positive.map(_* -1)

val stream = zero ++ positive.zip(negative).map(x => x._1.toString()+","+x._2.toString())
//stream.take(Int.MaxValue).toList

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Japt, 12 10 bytes

_OlU°,Un}a

Try it online!

Explanation:

_OlU°,Un}a
            | Implicit U = 0
_       }a  | Start an infinite loop
 Ol         | Write to the console:
   U°       |   U++
     ,      |    and
      Un    |   0-U
\$\endgroup\$
0
\$\begingroup\$

Gol><>, 7 bytes

lN01l-N

Try it online!

How it works

lN01l-N
l        push current stack length (n)
 N       pop and print with newline
  01l    push 0, 1, then stack length (n+2)
     -   pop n+2, 1, then push 1 - (n+2) = -n-1
      N  pop and print with newline
         now the stack length is n+1; repeat indefinitely
\$\endgroup\$
0
\$\begingroup\$

Zephyr, 48 bytes

set i to 0
while 1=1
print-i,i+1...
inc i
repeat

Space-separated. If the separator could alternate between space and newline, the ... could be removed for -3 bytes. Try it online!

\$\endgroup\$

protected by Community Nov 20 '17 at 13:16

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.