Integer sequence: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Delphi}}: Adds Déjà Vu example)
(Add a Limbo version.)
Line 732: Line 732:
wend
wend
</lang>
</lang>

=={{header|Limbo}}==
The int (32 bits) and big (64 bits) types are both signed, so they wrap around. This version uses the infinite precision integer library:

<lang Limbo>implement CountToInfinity;

include "sys.m"; sys: Sys;
include "draw.m";
include "ipints.m"; ipints: IPints;
IPint: import ipints;

CountToInfinity: module {
init: fn(nil: ref Draw->Context, nil: list of string);
};

init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
ipints = load IPints IPints->PATH;

i := IPint.inttoip(0);
one := IPint.inttoip(1);
for(;;) {
sys->print("%s\n", i.iptostr(10));
i = i.add(one);
}
}
</lang>


=={{header|Lua}}==
=={{header|Lua}}==

Revision as of 05:34, 4 January 2014

Task
Integer sequence
You are encouraged to solve this task according to the task description, using any language you may know.

Create a program that, when run, would display all integers from 1 to ∞ (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.

An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.

If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations—or lack thereof.

0815

<lang 0815>}:_:<:1:+%<:a:~$^:_:</lang>

Ada

<lang Ada>with Ada.Text_IO; procedure Integers is

  Value : Integer := 1;

begin

  loop
     Ada.Text_IO.Put_Line (Integer'Image (Value));
     Value := Value + 1;
  end loop;

end Integers;</lang> alternative (iterating through all values of Positive (positive part of Integer) without endless loop): <lang Ada>with Ada.Text_IO; procedure Positives is begin

  for Value in Positive'Range loop
     Ada.Text_IO.Put_Line (Positive'Image (Value));
  end loop;

end Positives;</lang>

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used.
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny.

The upper limit of the loop variable i is max int currently +2147483647 for ALGOL 68G. <lang algol68>main: (

 FOR i DO
   printf(($g(0)","$,i))
 OD

)</lang> Partial output:

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,...

Applesoft BASIC

Integer variables can be within the range of -32767 to 32767. <lang Applesoft BASIC> 10 I% = 1

20  PRINT I%;
30 I% = I% + 1
40  PRINT ", ";
50  GOTO 20</lang>

Last screen of scrolled output: <lang Applesoft BASIC>, 32646, 32647, 32648, 32649, 32650, 326 51, 32652, 32653, 32654, 32655, 32656, 3 2657, 32658, 32659, 32660, 32661, 32662,

32663, 32664, 32665, 32666, 32667, 3266

8, 32669, 32670, 32671, 32672, 32673, 32 674, 32675, 32676, 32677, 32678, 32679, 32680, 32681, 32682, 32683, 32684, 32685 , 32686, 32687, 32688, 32689, 32690, 326 91, 32692, 32693, 32694, 32695, 32696, 3 2697, 32698, 32699, 32700, 32701, 32702,

32703, 32704, 32705, 32706, 32707, 3270

8, 32709, 32710, 32711, 32712, 32713, 32 714, 32715, 32716, 32717, 32718, 32719, 32720, 32721, 32722, 32723, 32724, 32725 , 32726, 32727, 32728, 32729, 32730, 327 31, 32732, 32733, 32734, 32735, 32736, 3 2737, 32738, 32739, 32740, 32741, 32742,

32743, 32744, 32745, 32746, 32747, 3274

8, 32749, 32750, 32751, 32752, 32753, 32 754, 32755, 32756, 32757, 32758, 32759, 32760, 32761, 32762, 32763, 32764, 32765 , 32766, 32767 ?ILLEGAL QUANTITY ERROR IN 30 ]</lang>

AutoHotkey

This uses traytip to show the results. A msgbox, tooltip, or fileappend could also be used. <lang AutoHotkey>x=0 Loop

   TrayTip, Count, % ++x</lang>

AWK

<lang awk>BEGIN {

   for( i=0; i != i + 1; i++ )
       print( i )

}</lang>

Awk uses floating-point numbers. This loop terminates when i becomes too large for integer precision. With IEEE doubles, this loop terminates when i reaches 2 ^ 53.

BASIC

Works with: ZX Spectrum Basic

<lang basic>10 LET A = 0 20 LET A = A + 1 30 PRINT A 40 GO TO 20</lang>

Works with: QBasic

<lang qbasic>A = 0 DO: A = A + 1: PRINT A: LOOP 1</lang>

BBC BASIC

Native version, limited to 53-bit integers (maximum output 9007199254740992): <lang bbcbasic> *FLOAT 64

     REPEAT
       i += 1
       PRINT TAB(0,0) i;
     UNTIL FALSE</lang>

Version using Huge Integer Math and Encryption library (up to 2^31 bits, but this program limited to 65535 decimal digits because of maximum string length): <lang bbcbasic> INSTALL @lib$+"HIMELIB"

     PROC_himeinit("")
     reg% = 1
     
     PROC_hiputdec(reg%, "0")
     REPEAT
       SYS `hi_Incr`, ^reg%, ^reg%
       PRINT TAB(0,0) FN_higetdec(reg%);
     UNTIL FALSE</lang>

Bracmat

Translation of: Ruby

Bracmat uses big numbers. Numbers are stored with a radix 10, each decimal digit occupying one byte. When multiplying or dividing, numbers are temporarily converted to radix 10000 (32-bit systems: 1 digit occupies two bytes) or radix 100000000 (64-bit systems: 1 digit occupies four bytes) to speed up the computation. <lang>0:?n&whl'out$(1+!n:?n)</lang>

Brainf***

This program assumes that decrementing past zero wraps around, but it doesn't rely on cell size, other than that a cell can hold at least six bits. It also assumes the ASCII character set. This is an arbitrarily large number implementation. <lang brainf***>++++++++++>>>+[[->>+<[+>->+<<---------------------------------------


[>>-<++++++++++<[+>-<]]>[-<+>]<++++++++++++++++++

++++++++++++++++++++++++++++++>]<[<]>>[-<+++++++++++++++++++++++++++ ++++++++++++++++++++++>]>]>[>>>]<<<[.<<<]<.>>>+]</lang>

This modification of the previous program will print out 1 to the maximum cell value, still assuming wrapping. On many implementations, this will print out 1-255. <lang brainf***>++++++++++>>-[>+[->>+<[+>->+<<--------------------------------------


[>>-<++++++++++<[+>-<]]>[-<+>]<+++++++++++++++++

+++++++++++++++++++++++++++++++>]<[<]>>[-<++++++++++++++++++++++++++ +++++++++++++++++++++++>]>]>[>>>]<<<[.<<<]<.>>-]</lang>

Brat

<lang brat>i = 1

loop {

 p i
 i = i + 1

}</lang>

Burlesque

<lang burlesque> 1R@ </lang>

C

Prints from 1 to max unsigned integer (usually 2**32 -1), then stops. <lang c>#include <stdio.h>

int main() { unsigned int i = 0; while (++i) printf("%u\n", i);

return 0; }</lang>

Library: GMP

This one never stops. It's not even likely that you'll run out of memory before you run out of patience. <lang c>#include <gmp.h>

int main() { mpz_t i; mpz_init(i); /* zero now */

while (1) { mpz_add_ui(i, i, 1); /* i = i + 1 */ gmp_printf("%Zd\n", i); }

return 0; }</lang>

Library: OpenSSL

OpenSSL provides arbitrarily large integers.

<lang c>#include <openssl/bn.h> /* BN_*() */

  1. include <openssl/err.h> /* ERR_*() */
  2. include <stdio.h> /* fprintf(), puts() */

void fail(const char *message) { fprintf(stderr, "%s: error 0x%08lx\n", ERR_get_error()); exit(1); }

int main() { BIGNUM i; char *s;

BN_init(&i); for (;;) { if (BN_add_word(&i, 1) == 0) fail("BN_add_word"); s = BN_bn2dec(&i); if (s == NULL) fail("BN_bn2dec"); puts(s); OPENSSL_free(s); } /* NOTREACHED */ }</lang>

C#

<lang csharp>using System; using System.Numerics;

class Program {

   static void Main()
   {
       BigInteger i = 1;
       while (true)
       {
           Console.WriteLine(i++);
       }
   }

}</lang>

C++

<lang cpp>#include <iostream>

  1. include <cstdint>

int main() {

 uint32_t i = 0;
 while(true)
   std::cout << ++i << std::endl;
 return 0;

}</lang>

Clean

In Clean this example has a limit of basically 2147483648. <lang Clean>module IntegerSequence

import StdEnv

Start = [x \\ x <- [1..]]</lang>

Output:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,..

Clojure

<lang Clojure>(map println (next (range)))</lang>

COBOL

<lang cobol> IDENTIFICATION DIVISION.

      PROGRAM-ID. Int-Sequence.
      DATA DIVISION.
      WORKING-STORAGE SECTION.
  • *> 36 digits is the largest size a numeric field can have.
      01  I PIC 9(36).
      PROCEDURE DIVISION.
  • *> Display numbers until I overflows.
          PERFORM VARYING I FROM 1 BY 1 UNTIL I = 0
              DISPLAY I
          END-PERFORM
          GOBACK
          .</lang>

CoffeeScript

Like with most languages, counting is straightforward in CoffeeScript, so the program below tries to handle very large numbers. See the comments for starting the sequence from 1.

<lang coffeescript>

  1. This very limited BCD-based collection of functions
  2. makes it easy to count very large numbers. All arrays
  3. start off with the ones columns in position zero.
  4. Using arrays of decimal-based digits to model integers
  5. doesn't make much sense for most tasks, but if you
  6. want to keep counting forever, this does the trick.

BcdInteger =

 from_string: (s) ->
   arr = []
   for c in s
     arr.unshift parseInt(c)
   arr
 render: (arr) ->
   s = 
   for elem in arr
     s = elem.toString() + s
   s
   
 succ: (arr) ->
   arr = (elem for elem in arr)
   i = 0
   while arr[i] == 9
     arr[i] = 0
     i += 1
   arr[i] ||= 0
   arr[i] += 1
   arr
   
  1. To start counting from 1, change the next line!

big_int = BcdInteger.from_string "199999999999999999999999999999999999999999999999999999" while true

 console.log BcdInteger.render big_int
 big_int = BcdInteger.succ big_int

</lang>

output <lang> > coffee foo.coffee | head -5 199999999999999999999999999999999999999999999999999999 200000000000000000000000000000000000000000000000000000 200000000000000000000000000000000000000000000000000001 200000000000000000000000000000000000000000000000000002 200000000000000000000000000000000000000000000000000003 </lang>


Common Lisp

<lang lisp>(loop for i from 1 do (print i))</lang>

If your compiler does tail call elimination (note: this has absolutely no advantage over normal loops): <lang lisp>(defun pp (x) (pp (1+ (print x)))) (funcall (compile 'pp) 1) ; it's less likely interpreted mode will eliminate tails</lang>

Component Pascal

BlackBox Component Builder <lang oberon2> MODULE IntegerSequence; IMPORT StdLog;

PROCEDURE Do*; VAR i: INTEGER; BEGIN FOR i := 0 TO MAX(INTEGER) DO; StdLog.Int(i) END; StdLog.Ln END Do;

END IntegerSequence. </lang> Execute: ^Q IntegerSequence.Do
Output:

 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 ...

D

<lang d>import std.stdio, std.bigint;

void main() {

   BigInt i;
   while (true)
       writeln(++i);

}</lang> Alternative: <lang d>import std.stdio, std.traits, std.bigint, std.string;

void integerSequence(T)() if (isIntegral!T || is(T == BigInt)) {

   T now = 1;
   T max = 0;
   static if (!is(T == BigInt))
       max = T.max;
   do
       write(now, " ");
   while (now++ != max);
   writeln("\nDone!");

}

void main() {

   writeln("How much time do you have?");
   writeln(" 0. I'm in hurry.");
   writeln(" 1. I've some time.");
   writeln(" 2. I'm on vacation.");
   writeln(" 3. I'm unemployed...");
   writeln(" 4. I'm immortal!");
   write("Enter 0-4 or nothing to quit: ");
   string answer;
   readf("%s\n", &answer);
   switch (answer.toLower()) {
       case "0": integerSequence!ubyte();  break;
       case "1": integerSequence!short();  break;
       case "2": integerSequence!uint();   break;
       case "3": integerSequence!long();   break;
       case "4": integerSequence!BigInt(); break;
       default: writeln("\nBye bye!");     break;
   }

}</lang>

Dc

<lang Dc>1[p1+lpx]dspx</lang>

Delphi

<lang Delphi>program IntegerSequence;

{$APPTYPE CONSOLE}

var

 i: Integer;

begin

 for i := 1 to High(i) do
   WriteLn(i);

end.</lang>

Déjà Vu

<lang dejavu>1

while /= -- dup dup: !. dup ++

drop</lang>

This continues to print numbers until double precision IEEE 754 cannot represent adjacent integers any more (9007199254740992, to be exact).

In the future, the implementation may switch to arbitrary precision, so it will keep running until memory fills up.

DWScript

High(i) returns the maximum supported value, typically, it is the highest signed 64 bit integer. <lang delphi> var i: Integer;

for i:=1 to High(i) do

  PrintLn(i);

</lang>

E

<lang e>for i in int > 0 { println(i) }</lang>

Eiffel

<lang eiffel> class APPLICATION inherit ARGUMENTS create make feature {NONE} -- Initialization make -- Run application. do from number := 0 until number = number.max_value loop print(number) print(", ") number := number + 1 end end number:INTEGER_64 end </lang>

Emacs Lisp

Displays in the message area interactively, or to standard output under -batch.

<lang lisp>(dotimes (i most-positive-fixnum)

 (message "%d" (1+ i)))</lang>

Erlang

<lang erlang> F = fun(FF, I) -> io:format("~p~n", [I]), FF(FF, I + 1) end, F(F,0). </lang>

Euphoria

<lang euphoria>integer i i = 0 while 1 do

   ? i
   i += 1

end while</lang>

F#

<lang fsharp>// lazy sequence of integers starting with i let rec integers i =

 seq { yield i
       yield! integers (i+1) }

Seq.iter (printfn "%d") (integers 1)</lang>

lazy sequence of int32 starting from 0 <lang fsharp>let integers = Seq.initInfinite id</lang>

lazy sequence of int32 starting from n <lang fsharp>let integers n = Seq.initInfinite ((+) n)</lang>

lazy sequence (not necessarily of int32) starting from n (using unfold anamorphism) <lang fsharp>let inline numbers n =

   Seq.unfold (fun n -> Some (n, n + LanguagePrimitives.GenericOne)) n</lang>
> numbers 0 |> Seq.take 10;;
val it : seq<int> = seq [0; 1; 2; 3; ...]
> let bignumber = 12345678901234567890123456789012345678901234567890;;
val bignumber : System.Numerics.BigInteger =
  12345678901234567890123456789012345678901234567890
> numbers bignumber |> Seq.take 10;;
val it : seq<System.Numerics.BigInteger> =
 seq
   [12345678901234567890123456789012345678901234567890 {IsEven = true;
                                                        IsOne = false;
                                                        IsPowerOfTwo = false;
                                                        IsZero = false;
                                                        Sign = 1;};
    12345678901234567890123456789012345678901234567891 {IsEven = false;
                                                        IsOne = false;
                                                        IsPowerOfTwo = false;
                                                        IsZero = false;
                                                        Sign = 1;};
    12345678901234567890123456789012345678901234567892 {IsEven = true;
                                                        IsOne = false;
                                                        IsPowerOfTwo = false;
                                                        IsZero = false;
                                                        Sign = 1;};
    12345678901234567890123456789012345678901234567893 {IsEven = false;
                                                        IsOne = false;
                                                        IsPowerOfTwo = false;
                                                        IsZero = false;
                                                        Sign = 1;}; ...]
> numbers 42.42 |> Seq.take 10;;
val it : seq<float> = seq [42.42; 43.42; 44.42; 45.42; ...]

Factor

<lang factor>USE: lists.lazy 1 lfrom [ . ] leach</lang>

Fantom

<lang fantom> class Main {

 public static Void main()
 {
   i := 1
   while (true)
   {
     echo (i)
     i += 1
   }
 }

} </lang>

Fantom's integers are 64-bit signed, and so the numbers will return to 0 and continue again, if you wait long enough! You can use Java BigInteger via FFI

Fish

Since there aren't really libraries in Fish and I wouldn't know how to program arbitarily large integers, so here's an example that just goes on until the interpreter's number limit: <lang Fish>0>:n1+v

^o" "<</lang>

Forth

<lang forth>: ints ( -- )

 0 begin 1+ dup cr u. dup -1 = until drop ;</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>program Intseq

 implicit none
 
 integer, parameter :: i64 = selected_int_kind(18)
 integer(i64) :: n = 1
 

! n is declared as a 64 bit signed integer so the program will display up to ! 9223372036854775807 before overflowing to -9223372036854775808

 do
   print*, n
   n = n + 1
 end do

end program</lang>

GAP

<lang gap>InfiniteLoop := function() local n; n := 1; while true do Display(n); n := n + 1; od; end;

  1. Prepare some coffee

InfiniteLoop();</lang>

Go

Size of int type is implementation dependent, but I think all implementations use 32 bits currently. After the maximum positive value, it rolls over to maximum negative, without error. <lang go>package main

import "fmt"

func main() {

   for i := 1;; i++ {
       fmt.Println(i)
   }

}</lang> The big number type does not roll over and is limited only by available memory, or practically, by whatever external factor halts cpu execution: human operator, lightning storm, cpu fan failure, heat death of universe, etc. <lang go>package main

import (

   "big"
   "fmt"

)

func main() {

   one := big.NewInt(1)
   for i := big.NewInt(1);; i.Add(i, one) {
       fmt.Println(i)
   }

}</lang>

Groovy

<lang groovy>// 32-bit 2's-complement signed integer (int/Integer) for (def i = 1; i > 0; i++) { println i }

// 64-bit 2's-complement signed integer (long/Long) for (def i = 1L; i > 0; i+=1L) { println i }

// Arbitrarily-long binary signed integer (BigInteger) for (def i = 1g; ; i+=1g) { println i }</lang>

GUISS

Graphical User Interface Support Script makes use of installed programs. There are no variables, no loop structures and no jumps within the language so iteration is achieved by repetative instructions. In this example, we will just use the desktop calculator and keep adding one to get a counter. We stop after counting to ten in this example.

<lang guiss>Start,Programs,Accessories,Calculator, Button:[plus],Button:1,Button:[equals],Button:[plus],Button:1,Button:[equals], Button:[plus],Button:1,Button:[equals],Button:[plus],Button:1,Button:[equals], Button:[plus],Button:1,Button:[equals],Button:[plus],Button:1,Button:[equals], Button:[plus],Button:1,Button:[equals],Button:[plus],Button:1,Button:[equals], Button:[plus],Button:1,Button:[equals],Button:[plus],Button:1,Button:[equals]</lang>

Haskell

<lang haskell>mapM_ print [1..]</lang>

Or less imperatively:

<lang haskell>putStr $ unlines $ map show [1..]</lang>

Icon and Unicon

Icon and Unicon support large integers by default. The built-in generator seq(i,j) yields the infinite sequence i, i+j, i+2*j, etc. Converting the results to strings for display will likely eat your lunch before the sequence will take its toll.

<lang Icon>procedure main() every write(seq(1)) # the most concise way end</lang>

J

The following will count indefinitely but once the 32-bit (or 64-bit depending on J engine version) limit is reached, the results will be reported as floating point values (which would immediately halt on 64 bit J and halt with the 53 bit precision limit is exceeded on 32 bit J). Since that could take many, many centuries, even on a 32 bit machine, more likely problems include the user dying of old age and failing to pay the electric bill resulting in the machine being powered off.

<lang j> count=: (smoutput ] >:)^:_</lang>

The above works with both fixed sized integers and floating point numbers (fixed sized integers are automatically promoted to floating point, if they overflow), but also works with extended precision integers (which will not overflow, unless they get so large that they cannot be represented in memory, but that should exceed lifetime of the universe, let alone lifetime of the computer).

This adds support for extended precision (in that it converts non-extended precision arguments to extended precision arguments) and will display integers to ∞ (or at least until the machine is turned off or interrupted or crashes). <lang j> count=: (smoutput ] >:)@x:^:_</lang>

Java

Long limit: <lang java>public class Count{

   public static void main(String[] args){
       for(long i = 1; ;i++) System.out.println(i);
   }

}</lang> "Forever": <lang java>import java.math.BigInteger;

public class Count{

   public static void main(String[] args){
       for(BigInteger i = BigInteger.ONE; ;i = i.add(BigInteger.ONE)) System.out.println(i);
   }

}</lang>

JavaScript

<lang javascript>var i = 0;

while (true)

   document.write(++i + ' ');</lang>

Joy

<lang joy> 1 [0 >] [dup put succ] while pop.</lang>

Counting stops at maxint, which is 2147483647

Julia

<lang julia>i = zero(BigInt) # or i = big(0) while true

 println(i += 1)

end</lang> The built-in BigInt type is an arbitrary precision integer (based on the GMP library), so the value of i is limited only by available memory. To use (much faster) hardware fixed-width integer types, use e.g. zero(Int32) or zero(Int64). (Initializing i = 0 will use fixed-width integers that are the same size as the hardware address width, e.g. 64-bit on a 64-bit machine.)

K

<lang k> {`0:"\n",$x+:1;x}/1</lang>

Using a while loop:

<lang k> i:0; while[1;`0:"\n",$i+:1]</lang>

Lang5

<lang lang5>0 do dup . 1 + loop</lang>

Lasso

<lang Lasso>local(number = 1) while(#number > 0) => {^ #number++ ' ' //#number > 100 ? #number = -2 // uncomment this row if you want to halt the run after proving concept ^}</lang> This will run until you exhaust the system resources it's run under.

Liberty BASIC

Liberty BASIC handles extremely large integers. The following code was halted by user at 10,000,000 in test run. <lang lb> while 1

   i=i+1
   locate 1,1
   print i
   scan

wend

</lang>

Limbo

The int (32 bits) and big (64 bits) types are both signed, so they wrap around. This version uses the infinite precision integer library:

<lang Limbo>implement CountToInfinity;

include "sys.m"; sys: Sys; include "draw.m"; include "ipints.m"; ipints: IPints; IPint: import ipints;

CountToInfinity: module { init: fn(nil: ref Draw->Context, nil: list of string); };

init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; ipints = load IPints IPints->PATH;

i := IPint.inttoip(0); one := IPint.inttoip(1); for(;;) { sys->print("%s\n", i.iptostr(10)); i = i.add(one); } } </lang>

Lua

<lang lua> i = 1

-- in the event that the number inadvertently wraps around, -- stop looping - this is unlikely with Lua's default underlying -- number type (double), but on platform without double -- the C type used for numbers can be changed while i > 0 do

   print( i )
   i = i + 1

end </lang>

Mathematica

Built in arbitrary precision support meanst the following will not overflow. <lang Mathematica> x = 1; Monitor[While[True, x++], x] </lang>

MATLAB / Octave

<lang Matlab> a = 1; while (1) printf('%i\n',a); a=a+1; end; </lang>

Typically, numbers are stored as double precision floating point numbers, giving accurate integer values up to about 2^53=bitmax('double')=9.0072e+15. Above this limit, round off errors occur. This limitation can be overcome by defining the numeric value as type int64 or uint64

<lang Matlab> a = uint64(1); while (1) printf('%i\n',a); a=a+1; end; </lang>

This will run up to 2^64 and then stop increasing, there will be no overflow.

>> a=uint64(10e16+1)    % 10e16 is first converted into a double precision number causing some round-off error. 
a = 100000000000000000
>> a=uint64(10e16)+1
a = 100000000000000001

The above limitations can be overcome with additional toolboxes for symbolic computation or multiprecision computing.

Matlab and Octave recommend vectorizing the code, one might pre-allocate the sequence up to a specific N.

<lang Matlab> N = 2^30; printf('%d\n', 1:N); </lang>

The main limitation is the available memory on your machine. The standard version of Octave has a limit that a single data structure can hold at most 2^31 elements. In order to overcome this limit, Octave must be compiled with "./configure --enable-64", but this is currently not well supported.

Maxima

<lang maxima>for i do disp(i);</lang>

МК-61/52

<lang>1 П4 ИП4 С/П КИП4 БП 02</lang>

ML/I

<lang ML/I>MCSKIP "WITH" NL "" Integer sequence "" Will overflow when it reaches implementation-defined signed integer limit MCSKIP MT,<> MCINS %. MCDEF DEMO WITHS NL AS <MCSET T1=1 %L1.%T1. MCSET T1=T1+1 MCGO L1 > DEMO</lang>

NetRexx

Rexx Built In

NetRexx provides built-in support for very large precision arithmetic via the Rexx class. <lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary

k_ = Rexx bigDigits = 999999999 -- Maximum setting for digits allowed by NetRexx numeric digits bigDigits

loop k_ = 1

 say k_
 end k_

</lang>

Using BigInteger

Java's BigInteger class is also available for very large precision arithmetic. <lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary

import java.math.BigInteger

-- allow an option to change the output radix. parse arg radix . if radix.length() == 0 then radix = 10 -- default to decimal k_ = BigInteger k_ = BigInteger.ZERO

loop forever

 k_ = k_.add(BigInteger.ONE)
 say k_.toString(int radix)
 end

</lang>

Nimrod

<lang Nimrod> var i:int64 = 0 while true:

   i = i + 1
   echo(i)

</lang>

Objeck

<lang objeck> bundle Default {

 class Count {
   function : Main(args : String[]) ~ Nil {
     i := 0;
     do {
       i->PrintLine();
       i += 1;
     } while(i <> 0);
   }
 }

} </lang>

OCaml

with an imperative style: <lang ocaml>let () =

 let i = ref 0 in
 while true do
   print_int !i;
   print_newline ();
   incr i;
 done</lang>

with a functional style: <lang ocaml>let () =

 let rec aux i =
   print_int i;
   print_newline ();
   aux (succ i)
 in
 aux 0</lang>

OpenEdge/Progress

OpenEdge has three data types that can be used for this task:

  1. INTEGER (32-bit signed integer) <lang progress>DEF VAR ii AS INTEGER FORMAT "->>>>>>>>9" NO-UNDO. DO WHILE TRUE: ii = ii + 1. DISPLAY ii. END.</lang> When an integer rolls over its maximum of 2147483647 error 15747 is raised (Value # too large to fit in INTEGER.).
  2. INT64 (64-bit signed integer) <lang progress>DEF VAR ii AS INT64 FORMAT "->>>>>>>>>>>>>>>>>>9" NO-UNDO. DO WHILE TRUE: ii = ii + 1. DISPLAY ii. END.</lang> When a 64-bit integer overflows no error is raised and the signed integer becomes negative.
  3. DECIMAL (50 digits) <lang progress>DEF VAR de AS DECIMAL FORMAT "->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>9" NO-UNDO. DO WHILE TRUE: de = de + 1. DISPLAY de. END.</lang> When a decimal requires mores than 50 digits error 536 is raised (Decimal number is too large.).

Order

Order supports arbitrarily-large positive integers natively. However, the simple version: <lang c>#include <order/interpreter.h>

  1. define ORDER_PP_DEF_8printloop ORDER_PP_FN( \

8fn(8N, \

   8do(8print(8to_lit(8N) 8comma 8space),   \
       8printloop(8inc(8N)))) )

ORDER_PP( 8printloop(1) )</lang> ... while technically fulfilling the task, will probably never display anything, as most C Preprocessor implementations won't print their output until the file is done processing. Since the C Preprocessor is not technically Turing-complete, the Order interpreter has a maximum number of steps it can execute - but this number is very, very large (from the documentation: "the Order interpreter could easily be extended with a couple of hundred macros to prolong the wait well beyond the estimated lifetime of the sun"), so the compiler is rather more likely to simply run out of memory.

To actually see anything with GCC, add a maximum limit so that the task can complete: <lang c>#include <order/interpreter.h>

  1. define ORDER_PP_DEF_8printloop ORDER_PP_FN( \

8fn(8N, \

   8do(8print(8to_lit(8N) 8comma 8space),   \
       8when(8less(8N, 99), 8printloop(8inc(8N))))) )

ORDER_PP( 8printloop(1) ) // 1, ..., 99,</lang>

PARI/GP

<lang parigp>n=0; while(1,print(++n))</lang>

Pascal

See also Delphi

Works with: Free_Pascal

Quad word has the largest positive range of all ordinal types <lang pascal>Program IntegerSequenceLimited; var

 Number: QWord = 0; // 8 bytes, unsigned: 0 .. 18446744073709551615

begin

 repeat
   writeln(Number);
   inc(Number);
 until false;

end.</lang>

Library: GMP

With the gmp library your patience is probably the limit :-) <lang pascal>Program IntegerSequenceUnlimited;

uses

 gmp;

var

 Number: mpz_t;

begin

 mpz_init(Number); //* zero now *//
 repeat
   mp_printf('%Zd' + chr(13) + chr(10), @Number);
   mpz_add_ui(Number, Number, 1); //* increase Number *//
 until false;

end.</lang>

Perl

<lang perl>my $i = 0; print ++$i, "\n" while 1;</lang>

Perl 6

<lang perl6>.say for 1..*</lang>

PicoLisp

<lang PicoLisp>(for (I 1 T (inc I))

  (printsp I) )</lang>

PL/I

<lang PL/I> infinity: procedure options (main);

  declare k fixed decimal (30);
  put skip edit
     ((k do k = 1 to 999999999999999999999999999998))(f(31));

end infinity; </lang>

PostScript

Library: initlib

<lang postscript> 1 {succ dup =} loop </lang>

Prolog

<lang Prolog>loop(I) :- writeln(I), I1 is I+1, loop(I1). </lang>

Constraint Handling Rules

Works with SWI-Prolog and library CHR written by Tom Schrijvers and Jan Wielemaker <lang Prolog>:- use_module(library(chr)).

- chr_constraint loop/1.

loop(N) <=> writeln(N), N1 is N+1, loop(N1). </lang>

PureBasic

<lang PureBasic>OpenConsole() Repeat

 a.q+1
 PrintN(Str(a))

ForEver</lang>

Python

<lang python>i=1 while i:

   print(i)
   i += 1</lang>

Or, alternatively: <lang python>from itertools import count

for i in count():

   print(i)</lang>

Pythons integers are of arbitrary large precision and so programs would probably keep going until OS or hardware system failure.

Racket

Racket uses bignums, so counting should continue up to very large numbers. Naturally, printing these numbers will consume quite a bit of power.

<lang Racket>#lang racket (for ([i (in-naturals)]) (displayln i)) </lang>

Raven

Raven uses signed 32 bit integer values. <lang Raven>1 as $i repeat TRUE while

  $i "%d\n" print   $i 1000 +  as $i</lang>

Retro

Retro uses signed integer values.

<lang Retro>0 [ [ putn space ] sip 1+ dup 0 <> ] while drop</lang>

REXX

<lang rexx>/*count all the protons, electrons, & whatnot in the universe, and then */ /*keep counting. According to some pundits in-the-know, one version of */ /*the big-bang theory is that the universe will collapse back to where */ /*it started, and this computer program will be still counting. */ /*┌────────────────────────────────────────────────────────────────────┐

 │ Count all the protons  (and electrons!)  in the universe, and then │
 │ keep counting.  According to some pundits in-the-know, one version │
 │ of the big-bang theory is that the universe will collapse back to  │
 │ where it started, and this computer program will still be counting.│
 │                                                                    │
 │                                                                    │
 │ According to Sir Author Eddington in 1938 at his Tamer Lecture at  │
 │ Trinity Collecge (Cambridge), he postulated that there are exactly │
 │                                                                    │
 │                              136 ∙ 2^245                           │
 │                                                                    │
 │ protons in the universe and the same number of electrons, which is │
 │ equal to around  1.57477e+79.                                      │
 │                                                                    │
 │ Although, a modern extimate is around  10^80.                      │
 │                                                                    │
 │                                                                    │
 │ One estimate of the age of the universe is  13.7  billion years,   │
 │ or  4.32e+17 seconds.    This'll be a piece of cake.               │
 └────────────────────────────────────────────────────────────────────┘*/

numeric digits 1000000000 /*just in case the universe slows down. */

                               /*this version of a DO loop increments J*/
        do j=1                 /*Sir Eddington's number, then a googol.*/
        say j                  /*first, destroy some electrons.        */
        end

say 42 /*(see below for explanation of 42.) */ exit

/*This REXX program (as it will be limited to the NUMERIC DIGITS above, */ /*will only count up to 1000000000000000000000000000000000000000000... */ /*000000000000000000000000000000000000000000000000000000000000000000000 */ /* ... for another (almost) one billion more zeroes (then subtract 1).*/

/*if we can count 1,000 times faster than the fastest PeeCee, and we */ /*started at the moment of the big-bang, we'd be at only 1.72e+28, so */ /*we still have a little ways to go, eh? */

/*To clarify, we'd be 28 zeroes into a million zeroes. If PC's get */ /*1,000 times faster again, that would be 31 zeroes into a million. */

/*It only took Deep Thought 7.5 million years to come up with the */ /*answer to everything (and it double-checked the answer). It was 42.*/</lang>

Ruby

<lang ruby>i = 0 puts(i += 1) while true</lang>

Ruby does not limit the size of numbers.

Run BASIC

<lang runbasic>while 1 i = i + 1 print i wend</lang> Eventually as it gets larger it becomes a floating point.

Rust

<lang Rust>extern mod extra; use extra::bigint::BigUint; use std::num::One;

fn main() { let one: BigUint = One::one(); let mut i: BigUint = One::one();

loop { println(fmt!("%?", i.to_str())); i = i + one; } }</lang> Loops endlessly.

Salmon

Salmon has built-in unlimited-precision integer arithmetic, so these examples will all continue printing decimal values indefinitely, limited only by the amount of memory available (it requires O(log(n)) bits to store an integer n, so if your computer has 1 GB of memory, it will count to a number with on the order of digits).

<lang Salmon>iterate (i; [0...+oo])

   i!;</lang>

or

<lang Salmon>for (i; 0; true)

   i!;</lang>

or

<lang Salmon>variable i := 0; while (true)

 {
   i!;
   ++i;
 };</lang>

Scala

<lang scala>Stream from 1 foreach println</lang>

Scheme

<lang scheme> (let loop ((i 1))

 (display i) (newline)
 (loop (+ 1 i)))

</lang>

Scheme does not limit the size of numbers.

Seed7

Limit 2147483647: <lang seed7>$ include "seed7_05.s7i";

 const proc: main is func
   local
     var integer: number is 0;
   begin
     repeat
       incr(number);
       writeln(number);
     until number = 2147483647;
   end func;</lang>

"Forever": <lang seed7>$ include "seed7_05.s7i";

 include "bigint.s7i";
 const proc: main is func
   local
     var bigInteger: number is 1_;
   begin
     repeat
       writeln(number);
       incr(number);
     until FALSE;
   end func;</lang>

Smalltalk

<lang smalltalk>i := 0. [

  Stdout print:i; cr.
  i := i + 1

] loop</lang> will run forever.

Tcl

<lang tcl>package require Tcl 8.5 while true {puts [incr i]}</lang>

TUSCRIPT

<lang tuscript>$$ MODE TUSCRIPT LOOP n=0,999999999 n=n+1 ENDLOOP</lang>

UNIX Shell

<lang sh>#!/bin/sh num=0 while true; do

 echo $num
 num=`expr $num + 1`

done</lang>

Vala

<lang vala> uint i = 0; while (++i < uint.MAX) stdout.printf("%u\n", i); </lang>

Visual Basic .NET

Visual Basic .NET supports an unsigned, 64 bit Integer (maxing out at a whopping 9 223 372 036 854 775 807), however, this is not an intrinsic type, it is a structure that is not supported by the CLS (Common Language Specification).

The CLS supported type (also a structure) is Decimal (an even more impressive range from positive 79 228 162 514 264 337 593 543 950 335 to negative 79 228 162 514 264 337 593 543 950 335), I have used a standard CLS Integer intrinsic type (from -2 147 483 648 through 2 147 483 647).

Note that attempting to store any value larger than the maximum value of any given type (say 2 147 483 648 for an Integer) will result in an OverflowException being thrown ("Arithmetic operation resulted in an overflow.")

<lang vbnet> For i As Integer = 0 To Integer.MaxValue

     Console.WriteLine(i)
   Next</lang>

XPL0

<lang XPL0>\Displays integers up to 2^31-1 = 2,147,483,647 code CrLf=9, IntOut=11; int N; [N:= 1; repeat IntOut(0, N); CrLf(0);

       N:= N+1;

until N<0; ]</lang>