67
\$\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\$
25
  • 6
    \$\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, 2016 at 8:57
  • 7
    \$\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, 2016 at 9:10
  • 3
    \$\begingroup\$ @xnor Changed, though that kinds of ruins the very name of the challenge. \$\endgroup\$
    – Fatalize
    Sep 16, 2016 at 9:14
  • 6
    \$\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\$ Sep 16, 2016 at 9:54
  • 3
    \$\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, 2016 at 9:58

165 Answers 165

2
\$\begingroup\$

Brainfuck, 10 bytes

.+[>-.<.+]

Does not rely on cell wrapping to print the negative values. Does rely on accepting the cell value, which is commonly printed as a character by converting it to ASCII, to be the value to print.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Java, 49 bytes

o->{for(int n=1<<31;n<0;)o.println(n+"\n"+~n++);}

Notes:

  • o is a java.io.PrintStream but its import is not required given it's the parameter of a lambda expression.
  • This must be run on a Unix machine to properly use the same separator.

Ungolfed

import java.io.PrintStream;
import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        Consumer<PrintStream> func = o -> { // define the output and start the function.
          for (int n = 1 << 31; n < 0; n++) { // for each negative integer increasing from Integer.MIN_VALUE
            o.println(n + "\n" + ~n); // Print the negative number and its complement to 2 value.
          }
        };
        func.accept(System.out);
    }
}

Result

-2147483648
2147483647
-2147483647
2147483646
-2147483646
2147483645
-2147483645
2147483644
-2147483644
2147483643
-2147483643
2147483642
-2147483642
2147483641
-2147483641
2147483640
...
-7
6
-6
5
-5
4
-4
3
-3
2
-2
1
-1
0
\$\endgroup\$
2
\$\begingroup\$

R, 33 29 bytes

x=0;while(T)cat("",-x,x<-x+1)

Output (for < 10)

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

Explanation

It works because x is set to 0, then prints -0 which displays as 0. It then increments and prints that, giving 1. The next element is the negative value of the last which is -1 and so on...

EDIT: Cut it down by 4 bytes after I realised that I could just have it loop forever. In R, T is TRUE by default.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Hi, welcome to PPCG! Hmm, I've never programmed in R before, so correct me if I'm wrong, but doesn't this print 0 two times in the following sequence 0, 0, -1, 1, ...? \$\endgroup\$ Sep 19, 2016 at 13:06
  • 2
    \$\begingroup\$ It doesn't because it prints -0 (which prints as 0) then increments by 1 and prints that. An example of the output for x<10: 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 \$\endgroup\$ Sep 19, 2016 at 14:53
  • \$\begingroup\$ Ah ok, thanks for clarifying and adding the explanation. I was asking because I made a similar mistake with my own answer before, which printed 0 and -0 (second 0). Like I said, I never used R myself, so I knew there was a small chance I just didn't fully understand the code. +1 from me, and once again welcome. \$\endgroup\$ Sep 19, 2016 at 15:02
2
\$\begingroup\$

C 331 bytes

Note that this outperforms the long version as it really can do as many as memory will permit. It seems like it is bounded by strings of length max(size_t) which is true, but also definitionally the maximum memory that c will let us grab. Unfortunately it is very slow since it thrashes memory.

#include<stdlib.h>
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{return(_==1?printf("0\n"),main(2,0,0,1,0,0):_==2?main(3,"",0,c,0,0),main(2,0,0,c+1,0,0):_==3?(c?d=strlen(a),b=malloc(d),memcpy(b,a,d),b[d+1]=0,main(4,b,0,d,c-1,9),free(b),0:(*a-48?printf("%s\n-%s\n",a,a):0)):(e+1?a[c]=e+48,main(3,a,0,d,0,0),main(4,a,0,c,d,e-1):0));}

Prints 0, then 9,8,7,... then 99,98,97... etcetera. Can save 3 characters if we assume we don't care about output buffering (swapping \n for a space).

Process:

Initial

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// prints base 0...0, base 0...1, etc with remaining digits after it.
void print_digit_permutations(char *base, size_t remaining)
{
    int i;
    char *newbase = malloc(strlen(base)+1);

    if (!remaining) {
        if (*base != '0') 
            printf("%s\n-%s\n",base,base);
        return;
    }

    for (i = 0; base[i]; ++i) {
        newbase[i] = base[i];
    }
    newbase[strlen(base)+1] = 0;

    for (i = 0; i < 10; ++i) {
        newbase[strlen(base)] = i + '0';
        print_digit_permutations(newbase, remaining-1);
    }

    free(newbase);
}


int main()
{
    char *base = "";
    size_t i = 0;

    printf("0\n");

    for (;;) {
        print_digit_permutations(base, ++i);
    }

    return 0;
}

Unrolled

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void base_copy(char *newbase, char *base)
{
    if (*base) {
        *newbase = *base;
        base_copy(newbase+1,base+1);
    }
}

void print_digit_permutations(char*,size_t);
void print_all_digits(char *newbase, size_t baselen, size_t remaining, size_t count)
{
    if (count+1) {
        newbase[baselen] = count + '0';
        print_digit_permutations(newbase,remaining);
        print_all_digits(newbase,baselen,remaining,count-1);
    }
}

void print_digit_permutations(char *base, size_t remaining)
{
    int i;
    char *newbase = malloc(strlen(base)+1);

    if (!remaining) {
        if (*base != '0')
            printf("%s\n-%s\n",base,base);
        return;
    }

    base_copy(newbase,base);
    newbase[strlen(base)+1] = 0;

    print_all_digits(newbase,strlen(base),remaining-1,9);

    free(newbase);
}

void all(size_t size)
{
    print_digit_permutations("",size);
    all(size+1);
}

int main()
{
     printf("0\n");
     all(1);   

     return 0;
}

Flat

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _);
int print_all_digits(char *newbase, char *_, size_t baselen, size_t remaining, size_t count)
{
    return (count+1?
                newbase[baselen] = count + '0',
                print_digit_permutations(newbase,newbase,remaining,0,0),
                print_all_digits(newbase,newbase,baselen,remaining,count-1)
                :
                0);
}

int print_digit_permutations(char *base, char *newbase, size_t remaining, size_t baselen, size_t _)
{
    return (remaining?
            baselen=strlen(base),
            newbase = malloc(baselen),
            memcpy(newbase,base,baselen),
            newbase[baselen+1] = 0,
            print_all_digits(newbase,newbase,baselen,remaining-1,9),
            free(newbase),
            0
            :
            (*base-'0'?printf("%s\n-%s\n",base,base):0));
}

int all(char *_, char *_2, size_t size, size_t _3, size_t _4)
{
    return print_digit_permutations("","",size,0,0),
           all(_,_2,size+1,_3,_4);
}

int main()
{
    return printf("0\n"),all("","",1,0,0);
}

Main

#include <stdlib.h>
/* _ values:
 *
 * 1 - main
 * 2 - all 
 * 3 - print_digit_permutations
 * 4 - print_all_digits
 */
int main(_,a,b,c,d,e)char*a,*b;size_t c,d,e;{
    switch (_) {
        case 1:
            return printf("0\n"),main(2,0,0,1,0,0);
        case 2:
            return main(3,"",0,c,0,0),main(2,0,0,c+1,0,0);
        case 3:
            return (c?
                    d=strlen(a),
                    b=malloc(d),
                    memcpy(b,a,d),
                    b[d+1]=0,
                    main(4,b,0,d,c-1,9),
                    free(b),
                    0
                    :
                    (*a-'0'?printf("%s\n-%s\n",a,a):0));
        case 4:
            return (e+1?
                        a[c]=e+'0',
                        main(3,a,0,d,0,0),
                        main(4,a,0,c,d,e-1)
                        :0);
    }
}

And after removing whitespace and making a few other small changes we arrive at the initial golfed code. It is interesting that the 'proper' initial code is the second shortest at just over 700 bytes.

\$\endgroup\$
1
2
\$\begingroup\$

PHP, 28 27 bytes

for(;1;)echo 1-++$i," $i ";

As aross pointed out in the comments this only outputs PHP_INT_MIN (or indeed PHP_INT_MIN + 1) on a 32 bit implementation of php.

Old versions:

for(;++$i;)echo 1-$i," $i ";

If a leading space is allowed then

for(;++$i;)echo" $i ",1-$i;

Is 1 byte shorter. (same length as new version)

\$\endgroup\$
6
  • \$\begingroup\$ This won't output PHP_INT_MIN, so it's invalid \$\endgroup\$
    – aross
    Sep 26, 2016 at 8:23
  • \$\begingroup\$ sure it will, it switches over to a double representation which has enough precision to be accurate to php_int_min. \$\endgroup\$
    – user59178
    Sep 26, 2016 at 8:53
  • \$\begingroup\$ No it won't. Just set $i to a high number and let it run from there to see for yourself. It will output -9.2233720368548E+18 9.2233720368548E+18 (and will continue to output this for eternity). Adding 1 will not change the value of the float due to lack of precision. The last INTs in the output are -9223372036854775806 9223372036854775807 \$\endgroup\$
    – aross
    Sep 26, 2016 at 8:59
  • \$\begingroup\$ ah, maybe i should have been more precise: it will if you run it on a 32 bit version of php, such as php 5.6 on windows. where php_int_max is 2147483647 \$\endgroup\$
    – user59178
    Sep 26, 2016 at 9:34
  • \$\begingroup\$ So your answer is only valid in a very specific system, and you should note that \$\endgroup\$
    – aross
    Sep 26, 2016 at 9:40
2
\$\begingroup\$

PHP, 24 26 bytes

(24 bytes not displaying PHP_INT_MIN)

for(;;)echo-$i++," $i ";

Output : 0 1 -1 2 -2 3 -3 4 -4 5 -5 6 -6 7 -7 8 -8 9 -9 10 -10 ...

As $i is not defined, you have to cast it as integer (with - or +0)

(26 bytes not displaying PHP_INT_MIN)

for(;;)echo$i+++0," -$i ";

Output : 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 ...

\$\endgroup\$
4
  • \$\begingroup\$ This won't output PHP_INT_MAX, so it's invalid \$\endgroup\$
    – aross
    Sep 26, 2016 at 8:21
  • \$\begingroup\$ Sorry, it doesn't output PHP_INT_MIN \$\endgroup\$
    – aross
    Sep 26, 2016 at 9:28
  • \$\begingroup\$ Still won't output PHP_INT_MIN. Look at my answer \$\endgroup\$
    – aross
    Sep 29, 2016 at 14:27
  • \$\begingroup\$ I agree, I was editing. \$\endgroup\$
    – Crypto
    Sep 29, 2016 at 14:28
2
\$\begingroup\$

PHP, 27 26 bytes

Note that my answer actually outputs PHP_INT_MAX and PHP_INT_MIN, whereas others don't.

for(;;)echo+$i,_,~+$i++,_;

Run like this:

php -d error_reporting=30709 -r 'for(;;)echo+$i,_,~+$i++,_;';echo

This iterates from 0 to PHP_INT_MAX, obviously using post-increment to get the full range and not have an off-by-one error. Then get the negative range by XOR-ing with -1 binary negation.

INT_MAX and INT_MIN

A signed integer actually has a 1 bigger range of negative values than positive values. In the case of 64-bit int (PHP default on 64-bit systems) it's -9223372036854775808 upto 92233720368547758087 inclusive. Many answers stop at -9223372036854775807, which is 1 short.

To see the tail of the output (with PHP_INT_MAX and PHP_INT_MIN), just do this:

php -d error_reporting=30709 -r 'for($i=PHP_INT_MAX-5;is_int($i);)echo+$i,_,~+$i++,_;';echo

The is_int is strictly not needed, it just makes sure the loop stops when $i exceeds PHP_INT_MAX and becomes a float, outputting junk for all eternity.

Tweaks

  • Use binary negation instead of xor with -1. Requires another cast to int to handle the null case. Saved a byte.
\$\endgroup\$
2
\$\begingroup\$

LI, 16 7 bytes

New solution:

R-0P-1P

I feel kinda silly for not realizing I could have done this before. I'm keeping the other one because it shows off more flow control and more functions.

LI is a (very) WIP language that relies primarily on recursion. Every program in LI must take in user-provided input, so the given program here accepts LI's "null" input of 0.

The current Python interpreter is just barely enough to meet the specifications of this challenge, albeit wordy; I'm working on a Racket interpreter that would be able to meet the specs of this challenge with three bytes, but unfortunately it's not even close to challenge-ready.

Explanation:

      P    Print input
    -1     (1 - input)
   P       Print that too
 -0        (- (1 - input))
R          Rerun program with new input

Old solution:

R?>0i-0PyPi-0PYP

Roughly, this program translates to:

R                        Recurse program with input:
                 P        print-return (implicit input)
                Y         Increment input
               P          Print incremented
             -0           Invert sign
                          = -(i+1)
 ?>0i                   if i is not negative.
      -0PyPi            If i is negative, do the same but decrement (y) instead of increment.

For both solutions, output is of the following format:

0
1
-1
2
-2
3
-3
...

The default interpreter will run out of memory at -3338 (3342 with the new solution), if you're curious.

\$\endgroup\$
2
2
\$\begingroup\$

Rust, 39 bytes

||for i in 0..{print!(" {} {}",i,-1-i)}

This uses i32. adding i64 right behind the zero would make it use that instead at a cost of 3 more bytes. Rust has no bignum types in the standard library. When overflowing, this will either panic or quietly wrap around, depending on compiler options.

\$\endgroup\$
2
\$\begingroup\$

q KDB+, 25 bytes

n:-0W;while[n<0W;0N!n+:1]

Set n to negative infinity.

n:-0W

Increment and output n.

0N!n+:1

Loop until n < infinity.

n<0W

Possible alternate 17 bytes

(0N!1+)\[0W>;-0W]

Uses the \ (iterate) dyadic function to apply left hand side (plus 1 then output) from negative infinity (-0W) to infinity(0W).

Only problem is that it may throw a wsfull error eventually or at the very end after outputting all the integers.

\$\endgroup\$
2
\$\begingroup\$

Powershell, 26 19 Bytes

for(){($b++);$b*-1}

updated because I should have done it months ago.

very straightforward, takes a variable $a, initializes as 0, then initiates an infinite loop with while(1){} and then displays the current value $a - increments it $a++ and displays the negative version of it $a*-1

output is automatically on a new line for each display, so the resulting output is:

0
-1
1
-2
2
-3
3
-4
\$\endgroup\$
2
  • \$\begingroup\$ Nice to see another PowerShell golfer around! You could swap the while for a for, change how $b is initialized by encapsulating it in parens to place a copy on the pipeline, and turn $b*-1 into -$b. That gets you down to 17 -- for(){($b++);-$b} ... outputs 0 -1 1 -2 2... with newlines in between. \$\endgroup\$ Oct 7, 2016 at 18:51
  • \$\begingroup\$ didn't realize you could use a blank for - thought you needed to use for(;;) which is the same bytes as while() - thanks for the tips! \$\endgroup\$
    – colsw
    Oct 8, 2016 at 13:53
2
\$\begingroup\$

tcl, 35

puts 0
while 1 {puts [incr i]\n-$i}

demo

\$\endgroup\$
2
\$\begingroup\$

><>, 17 16 Bytes

0:n1+ao:0$-nao0?

Could shave off 4 bytes, at the cost of separation in the output.

Current output:

0
-1
1
-2
2
...

Explanation:

0:n                          | Puts 0 on the stack, duplicates it, and prints it.
   1+                        | Increments the value
     ao                      | Prints a new line.
       :0$-n                 | Duplicates the value, prints it negative.
            ao               | Print a new line.
              0?             | Skip the next command (pushing 0), repeat.

Previous solution:

0:n1+ao:0$-nao01.

Teleports to the command after the 0, instead of just skipping it.

\$\endgroup\$
2
\$\begingroup\$

SmileBASIC, 20 bytes

@L?N,-N-1N=N+1GOTO@L

A very boring answer.

Alternative:

@L?N
INC N?-N
GOTO @L
\$\endgroup\$
2
  • \$\begingroup\$ This will print 0 twice, making it an invalid answer. "print every integer exactly once" \$\endgroup\$
    – snail_
    Mar 29, 2018 at 8:44
  • 1
    \$\begingroup\$ Welll.... technically it prints negative 0 -0... But now it's fixed. \$\endgroup\$
    – 12Me21
    Mar 29, 2018 at 14:55
2
\$\begingroup\$

GolfScript, 16 14 bytes

1{.p.1\-p).}do

Explanation:

1              # Set counter to 1
 {        .}do # While counter is nonzero:
  .p           # Print counter
    .1\-p      # Print counter - 1
         )     # Increment counter by 1

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Wren, 50 bytes

var n=0
while(n)n=-System.print(1-System.print(n))

Try it online!

Explanation

var n=0 // Set n as 0
while(n)                                   // While n is an integer:
                          System.print(n)  // Output n
           System.print(1-               ) // Output 1-n
        n=-                                // Set n as the number negated
\$\endgroup\$
2
\$\begingroup\$

Runic Enchantments, 24 bytes

8?;>0$' $01+:$' $Z:$' $Z

Try it online!

' $ is just as long as any other way of printing a character (such as ak$) so with a required separator, that's as short as it gets.

Will print forever until the value exceeds the binary representation and sign-overflows (which is acceptable for questions with an infinite memory assumption), whereupon it will repeat.

\$\endgroup\$
2
\$\begingroup\$

Python 2, 32 bytes

i=0
while 1:print i;print~i;i+=1
\$\endgroup\$
2
  • \$\begingroup\$ You could also do i=0 (newline) while 1:print i;print~i;i+=1 if you wanted \$\endgroup\$ Dec 29, 2016 at 18:16
  • 2
    \$\begingroup\$ If you need rep for your chat bot account, consider making a meaningful contribution to the site. This adds absolutely nothing over the pre-existing 27 byte Python answer. \$\endgroup\$
    – Dennis
    Dec 29, 2016 at 22:34
2
\$\begingroup\$

x86-16, IBM PC DOS, 47 bytes

Binary:

00000000: 33c9 bd0a 0050 0bc0 7d09 50b8 2d0e cd10  3....P..}.P.-...
00000010: 58f7 d833 d2f7 f552 410b c075 f658 b40e  X..3...RA..u.X..
00000020: 0c30 cd10 e2f7 b020 cd10 5840 75d7 c3    .0..... ..X@u..

Build and test using xxd -r

Unassembled listing:

33 C9       XOR  CX, CX         ; clear counter
B3 0A       MOV  BL, 10         ; BX is divisor              
        INT_LOOP: 
50          PUSH AX             ; save registers 
0B C0       OR   AX, AX         ; is AX negative? 
7D 09       JGE  DIGIT_LOOP     ; if positive, start digit loop 
50          PUSH AX             ; save number 
B8 0E2D     MOV  AX, 0E2DH      ; BIOS tty function, '-' char output 
CD 10       INT  10H            ; write to console 
58          POP  AX             ; restore AX 
F7 D8       NEG  AX             ; AX = -AX                
        DIGIT_LOOP: 
33 D2       XOR  DX, DX         ; clear high word of dividend   
F7 F3       DIV  BX             ; AX = quotient, DX = remainder 
52          PUSH DX             ; save remainder on stack 
41          INC  CX             ; increment counter 
0B C0       OR   AX, AX         ; quotient = 0?
75 F6       JNE  DIGIT_LOOP     ; no, keep going 
        PRINT_LOOP: 
58          POP  AX             ; restore digit in AL 
B4 0E       MOV  AH, 0EH        ; BIOS tty function 
0C 30       OR   AL, '0'        ; convert to ASCII 
CD 10       INT  10H            ; write to console 
E2 F7       LOOP PRINT_LOOP     ; loop until all digits displayed 
B0 20       MOV  AL, ' '        ; space char 
CD 10       INT  10H            ; write to console 
58          POP  AX             ; restore counter 
40          INC  AX             ; increment to next number 
75 D7       JNZ  INT_LOOP       ; loop until 0 
C3          RET                 ; return to DOS

(This program is basically just an itoa() function...)

Output

A standalone DOS executable. Using default 16-bit integer size for 8088, writes all numbers in decimal to console.

Head:

enter image description here

Tail:

enter image description here

\$\endgroup\$
2
\$\begingroup\$

W d, 6 5 bytes

Newline-separated. Look ma, no bitwise magic!

▲h(2Z

Explanation

Decompressed:

0      % Print 0 (the implicit not-given operand, to be precise)
 i   E % In the range 1..infinity...
  a    % Explicit loop variable
   P   % Print the number with a newline
    _  % Negate the number
       % Implicit print on each iteration
       % Make sure that the second-to-top executes (this is now implicit)
\$\endgroup\$
2
\$\begingroup\$

MathGolf, 8 bytes

0Æ∙p~p)∟

Try it online.

Explanation:

0         # Push a 0
       ∟  # Do-while true without popping,
 Æ        # using the following 5 commands:
  ∙       #  Triplicate the top of the stack
   p      #  Pop and print with trailing newline
    ~     #  Take the bitwise-NOT
     p    #  Also pop and print it with trailing newline
      )   #  And increase the top value by 1
\$\endgroup\$
2
\$\begingroup\$

LaTeX, 97 bytes

\def\f{\typeout0\newcount\n\n=1\loop\typeout{\the\n}\typeout{-\the\n}\advance\n1\ifnum1=1\repeat}

Defines a macro \f that writes to stdout.

Explanation

\def\f{                % define a macro \f
  \typeout0             % write a 0
  \newcount\n           % define a new counter n
  \n=1                  % set n to 1
  \loop                 % this is like a do-while loop
    \typeout{\the\n}     % write n
    \typeout{-\the\n}    % write -n
    \advance \n 1        % increment n by 1
  \ifnum 1=1            % this is the loop condition, continue if 1=1
  \repeat               % jump to the loop start
}
\$\endgroup\$
2
\$\begingroup\$

Turing Machine Code, 460 bytes

This prints the list in Unary so I'm hoping this still counts since, in Turing Machine Code, the concept of a 'number base' isn't built in. I'm going to mull over a base ten solution and post it separately if it exists and I find it.

0 * 1 r 2
2 * , r 3
3 * - r 4
4 * 1 r 5
5 * * r 5
5 _ , r 6
6 * * r 6
6 _ 1 * 7
7 * * l 7
7 , , l 8
8 * * l 8
8 - - r 9
9 1 @ r a
8 , , r g
g 1 @ r a
g - - r a
a * * r a
a _ 1 l b
b * * l b
b @ 1 r c
c 1 @ r a
c , , r d
d * * l d
d - - r 6
d , , r e
e * * r e
e _ , r f
f _ - r h
h * * l h
h , , l i
i * * l i
i , , r j
j 1 @ r k
j , , r m
k * * r k
m * * r m
m _ , r n
k _ 1 * o
o * * l o
o , , l p
p * * l p 
p , , r q
p @ 1 r j
q * * r q
q _ , r n
n _ 1 r 7

Try it online!

\$\endgroup\$
2
\$\begingroup\$

F# (.NET Core), 46 bytes

My first F# golf.

let rec c x=
 printf"%d,%d,"(1-x)x
 x+1|>c
c 1

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Add++ v0.2, 23 bytes

This is the current version on TIO. The latest should be able to do it in less but it is untested so I decided not to post it.

O
V
+1
W,G,+1,O,~,O,~,V

Try it online!

How does it work?

O      Output the accumulator (x) as a number (0)
V      Save x in the second stack
+1     Add one to x
W,     While x is true:
  G,     Set x to the popped item from the second stack
  +1,    Add 1 to x
  O,     Output x as a number
  ~,     Negate x
  O,     Output x as a number
  ~,     Negate x
  V      Save x in the second stack

Add++ v5.10, 13 bytes

Dx,O,#,+1,O,#

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Vyxal, 7 bytes

0…{!…N…

Try it Online!

\$\endgroup\$
2
\$\begingroup\$

APL, 17 bytes

Pretty self explanatory

{∇⊃⎕←(⊢,-)1+⍵}⎕←0
\$\endgroup\$
2
\$\begingroup\$

Vyxal, 13 bitsv2, 1.625 bytes

Þn

Built-in list containing all integers.

Try it Online!

\$\endgroup\$
2
\$\begingroup\$

Befunge-93, 8 bytes

.1+::&*.

Try it online!

Explanation

v // Make this explanation be able to run (downwards)
. // Print top of stack as integer (if first iteration, stack is initialized at 0, so 0 is the first integer printed)
1
+ // Increment
:
: // Duplicate number so it isn't lost doing operations and printing
&
* // Negate. When input is empty, getting user input with & returns -1.
. // Output negative integer
  // Continue to next iteration, where top of stack (positive integer) will get printed

Try it online!

\$\endgroup\$
1
\$\begingroup\$

Caché ObjectScript, 28 bytes

w 0 f i=1:1 {w ",",i,",",-i}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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