Integer sequence
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.
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
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
}:_:<:1:+%<:a:~$^:_:
11l
L(i) 1..
print(i)
360 Assembly
For maximum compatibility, this program uses only the basic instruction set (S/360).
* Integer sequence 06/05/2016
INTSEQED CSECT
USING INTSEQED,12
LR 12,15
LA 6,1 i=1
LOOP CVD 6,DW binary to pack decimal
MVC WTOMSG+4(12),EM12 load mask
ED WTOMSG+4(12),DW+2 packed dec to char
WTO MF=(E,WTOMSG) write to console
LA 6,1(6) i=i+1
B LOOP goto loop
WTOMSG DC 0F,H'80',H'0',CL80' '
DW DS 0D,PL8 pack dec 15num
EM12 DC X'402020202020202020202120' mask CL12 11num
END INTSEQED
- Output:
... 314090 314091 314092 314093 314094 314095 314096 314097 314098 314099 ...
6502 Asembler
I no longer have my personal copy of: 6502 assembly language subroutines by Lance A. Leventhal, Winthrop Saville pub Osborne/McGraw-Hill (destroyed in bushfire) It is available on the Wayback Machine (archive.org) Pages 253ff contains a general purpose Multiple-Precision Binary Addition subroutine Not needing to re-invent the wheel, I used this as the basis for my solution.
.multiple_precision_add
8080 Assembly
Actually printing the numbers out would depend on the hardware and operating system.
ORG 0100H
MVI A, 0 ; move immediate
LOOP: INR A ; increment
; call 'PRINT' subroutine, if required
JMP LOOP ; jump unconditionally
END
A more complex, arbitrary precision version that can count as high as you have free bytes of memory to use. (This does assemble with CP/M's MAC assembler, but since it doesn't implement PRBUFR, it's only useful for exposition purposes, or for loading into DDT.)
ORG 0100H
BITS EQU 128 ; 128 bits of precision
BYTES EQU BITS / 8 ; Number of bytes we store those bits in
; Zero out the storage for our number
LXI H,BUFR ; HL points at BUFR. (HL is idiomatically used for pointers)
MVI C,BYTES ; C holds the number of bytes we'll use
XRA A ; XOR with A is a 1-byte instruction to set A to zero
INIT: MOV M,A ; Store 0 to address pointed to by HL
INX H ; Advance HL to the next byte
DCR C ; Count down
JNZ INIT ; Keep looping if we're not done
; The "very long integer" is zeroed, so start the loop
LOOP: CALL PRBUFR ; Output our number
LXI H,BUFR ; HL Points to BUFR
MVI C,BYTES ; Count down (assume fewer than 256 bytes in our integer)
NEXT: INR M ; Increment the byte pointed to by HL. Sets the zero flag
JNZ LOOP ; If the increment didn't overflow A, start the loop over
; This byte overflowed, so we need to advance to the next byte in our number
INX H ; We store our byes in order of increasing significance
DCR C ; Count down to make sure we don't overflow our buffer
JNZ NEXT ; jump to process the next, more significant byte
; If we get here, we have overflowed our integer!
HALT ; TODO: probably something other than "halt the CPU"
PRBUFR: ; TODO, a subroutine that shows all of the digits in BUFR on the console
; Assume that this code trashes all our registers...
RET
BUFR: ; This space will hold our number
; We zero this memory before the loop
END
Action!
PROC Main()
CARD i
i=0
DO
PrintF("%U ",i)
i==+1
UNTIL i=0
OD
RETURN
- Output:
Screenshot from Atari 8-bit computer
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 ...
Ada
with Ada.Text_IO;
procedure Integers is
Value : Integer := 1;
begin
loop
Ada.Text_IO.Put_Line (Integer'Image (Value));
Value := Value + 1; -- raises exception Constraint_Error on overflow
end loop;
end Integers;
Alternative (iterating through all values of Positive (positive part of Integer) without endless loop):
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;
ALGOL 68
The upper limit of the loop variable i is max int currently +2147483647 for ALGOL 68G.
main:
(
FOR i DO
printf(($g(0)","$,i))
OD
)
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,...
ALGOL W
begin
% print the integers from 1 onwards %
% Algol W only has 32-bit integers. When i reaches 2^32, %
% an integer overflow event would be raised which by default, %
% should terminate the program %
integer i;
i := 1;
while true do begin
write( i );
i := i + 1
end loop_forever ;
end.
Applesoft BASIC
Integer variables can be within the range of -32767 to 32767.
10 I% = 1
20 PRINT I%;
30 I% = I% + 1
40 PRINT ", ";
50 GOTO 20
Last screen of scrolled output:
, 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
]
ARM Assembly
.text
.global main
@ An ARM program that keeps incrementing R0 forever
@
@ If desired, a call to some 'PRINT' routine --
@ which would depend on the OS -- could be included
main:
mov r0, #0 @ start with R0 = 0
repeat:
@ call to 'PRINT' routine
add r0, r0, #1 @ increment R0
b repeat @ unconditional branch
Alternative version
Developed on an Acorn A5000 with RISC OS 3.10 (30 Apr 1992) Using the assembler contained in ARM BBC BASIC V version 1.05 (c) Acorn 1989 The Acorn A5000 is the individual computer used to develop the code, the code is applicable to all the Acorn Risc Machines (ARM) produced by Acorn and the StrongARM produced by digital. Investigation (a) If all that was needed was to increment without doing the required display part of the task then: .a_loop ADDS R0 , R0, #1 ADCS R1 , R1, #0 ADCS R2 , R2, #0 ADCS R3 , R3, #0 B a_loop will count a 128 bit number Investigation (b) How long does it take? .b_loop_01 \ took 71075 cs = 11.85 mins ADDS R0, R0, #1 \ only a single ADD in the loop - unable to get the pipeline going B B_loop_01 .b_loop_04 \ took 31100 cs = 5.18 mins ADDS R0, R0, #1 \ with four instructions within the loop ADDS R0, R0, #1 ADDS R0, R0, #1 ADDS R0, R0, #1 B B_loop_04 .b_loop_16 \ took 21112 cs = 3.52 mins ADDS R0, R0, #1 \ with sixteen instructions within the loop followed by a further 15 ADDS instructions B B_loop_16 so there clearly is a time advantage to putting enough inline instructions to make the pipeline effective But beware - for a 64 bit number (paired ADDS and ADCS) it took 38903 cs = 6.48 mins to count to only 32 bits, a 128 bit number will take 4,294,967,296 * 4,294,967,296 * 4,294,967,296 times 6.48 mins. My pet rock will tell you how long that took as it will have evolved into a sentient being by then. The task Producing a solution in say 64 bits or 128 bits is trivial when only looking at the increment. Hovever the display part of the task is very difficult. So instead go for BCD in as many bits as required. This makes the increment more involved, but the display part of the task becomes manageable. So a solution is: .bcd_32bits_vn02 MOV R4 , #0 \ if eventually 4 registers each with 8 BCD MOV R5 , #0 \ then 32 digits total MOV R6 , #0 MOV R7 , #0 MOV R8 , #0 \ general workspace MOV R9 , #0 \ a flag in the display - either doing leading space or digits MVN R10 #&0000000F \ preset a mask of &FFFFFFF0 \ preset in R10 as the ARM has a very limited \ range of immediate literals MOV R11 , #&F \ preset so can be used in AND etc together with shifts B bcd_32bits_loop_vn02 \ intentionally jump to inside the loop as this \ single branch saves the need for multiple branches \ later on (every branch resets the instruction pipeline) \ the repeated blocks of code could be extracted into routines, however as they are small \ I have decided to keep them as inline code as I have decided that the improved execution \ from better use of the pipeline is greater than the small overall code size .bcd_32bits_display_previous_number_vn02 MOV R9 , #0 \ start off with leading spaces (when R9<>0 output "0" instead) ANDS R8 , R11 , R4, LSR#28 \ extract just the BCD in bits 28 to 31 of R4 MOVNE R9 , #1 \ if the BCD is non-zero then stop doing leading spaces CMP R9 , #0 \ I could not find a way to eliminate this CMP MOVEQ R0 , #&20 \ leading space ORRNE R0 , R8 , #&30 \ digit 0 to 9 all ready for output SWI OS_WriteC \ output the byte in R0 ANDS R8 , R11 , R4, LSR#24 \ extract just the BCD in bits 24 to 27 of R4 MOVNE R9 , #1 CMP R9 , #0 MOVEQ R0 , #&20 ORRNE R0 , R8 , #&30 SWI OS_WriteC ANDS R8 , R11 , R4, LSR#20 \ extract just the BCD in bits 20 to 23 of R4 MOVNE R9 , #1 CMP R9 , #0 MOVEQ R0 , #&20 ORRNE R0 , R8 , #&30 SWI OS_WriteC ANDS R8 , R11 , R4, LSR#16 \ extract just the BCD in bits 16 to 19 of R4 MOVNE R9 , #1 CMP R9 , #0 MOVEQ R0 , #&20 ORRNE R0 , R8 , #&30 SWI OS_WriteC ANDS R8 , R11 , R4, LSR#12 \ extract just the BCD in bits 12 to 15 of R4 MOVNE R9 , #1 CMP R9 , #0 MOVEQ R0 , #&20 ORRNE R0 , R8 , #&30 SWI OS_WriteC ANDS R8 , R11 , R4, LSR#8 \ extract just the BCD in bits 8 to 11 of R4 MOVNE R9 , #1 CMP R9 , #0 MOVEQ R0 , #&20 ORRNE R0 , R8 , #&30 SWI OS_WriteC ANDS R8 , R11 , R4, LSR#4 \ extract just the BCD in bits 4 to 7 of R4 MOVNE R9 , #1 CMP R9 , #0 MOVEQ R0 , #&20 ORRNE R0 , R8 , #&30 SWI OS_WriteC \ have reached the l.s. BCD - so will always output a digit, never a space AND R8 , R11 , R4 \ extract just the BCD in bits 0 to 3 of R4 ORR R0 , R8 , #&30 \ digits 0 to 9 all ready for output SWI OS_WriteC \ output the byte in R0 MOV R0 , #&13 \ carriage return SWI OS_WriteC MOV R0 , #&10 \ line feed SWI OS_WriteC \ there is no need for a branch instruction here \ instead just fall through to the next increment .bcd_32bits_loop_vn02 ADD R4 , R4 , #1 \ increment the l.s. BCD in bits 0 to 3 AND R8 , R4 , #&F \ extract just the BCD nibble after increment CMP R8 , #10 \ has it reached 10? \ if not then about to branch to the display code BLT bcd_32bits_display_previous_number_vn02 \ have reached 10 ANDEQ R4 , R4 , R10 \ R10 contains &FFFFFFF0 so the BCD is set to 0 \ but now need to add in the carry to the next BCD \ I have noticed that the EQ is superfluous here \ but it does no harm \ now work with the nibble in bits 4 to 7 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 \ rotate R4 right by 4 bits ADD R4 , R4 , #1 \ add in the carry AND R8 , R4 , #&F \ extract just the BCD nibble after carry added CMP R8 , #10 \ has it reached 10? \ if less than 10 then rotate back to correct place \ then branch to the display code MOVLT R4 , R4 , ROR #28 \ finished adding in carry - rotate R4 right by 32-4=28 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ R10 contains &FFFFFFF0 so the BCD is set to 0 \ but now need to add in the carry to the next BCD \ now work with the nibble in bits 8 to 11 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 \ rotate R4 right by 4 bits ADD R4 , R4 , #1 \ add in the carry AND R8 , R4 , #&F \ extract just the BCD nibble after carry added CMP R8 , #10 \ has it reached 10? \ if less than 10 then rotate back to correct place \ then branch to the display code MOVLT R4 , R4 , ROR #24 \ finished adding in carry - rotate R4 right by 32-8=24 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ now work with the nibble in bits 12 to 15 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 ADD R4 , R4 , #1 AND R8 , R4 , #&F CMP R8 , #10 MOVLT R4 , R4 , ROR #20 \ finished adding in carry - rotate R4 right by 32-12=20 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ now work with the nibble in bits 16 to 19 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 ADD R4 , R4 , #1 AND R8 , R4 , #&F CMP R8 , #10 MOVLT R4 , R4 , ROR #16 \ finished adding in carry - rotate R4 right by 32-16=16 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ now work with the nibble in bits 20 to 23 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 ADD R4 , R4 , #1 AND R8 , R4 , #&F CMP R8 , #10 MOVLT R4 , R4 , ROR #12 \ finished adding in carry - rotate R4 right by 32-20=12 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ now work with the nibble in bits 24 to 27 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 ADD R4 , R4 , #1 AND R8 , R4 , #&F CMP R8 , #10 MOVLT R4 , R4 , ROR #8 \ finished adding in carry - rotate R4 right by 32-24=8 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ now work with the nibble in bits 28 to 31 (bit 31 is m.s. and bit 0 is l.s.) MOV R4 , R4 , ROR #4 ADD R4 , R4 , #1 AND R8 , R4 , #&F CMP R8 , #10 MOVLT R4 , R4 , ROR #4 \ finished adding in carry - rotate R4 right by 32-28=4 bits BLT bcd_32bits_display_previous_number_vn02 \ yet another carry ANDEQ R4 , R4 , R10 \ to continue the carry needs to be added to the next register (probably R5) if more than 8 BCD are required \ if yet more than 16 BCD then continue to the next register (R6) \ the extra code required will be as above but using R5 (or R6) instead of R4 MOVS PC , R14 \ return
ArnoldC
IT'S SHOWTIME
HEY CHRISTMAS TREE n
YOU SET US UP @NO PROBLEMO
STICK AROUND @NO PROBLEMO
TALK TO THE HAND n
GET TO THE CHOPPER n
HERE IS MY INVITATION n
GET UP @NO PROBLEMO
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED
Arturo
i:0
while ø [
print i
inc 'i
]
AutoHotkey
This uses traytip to show the results. A msgbox, tooltip, or fileappend could also be used.
x=0
Loop
TrayTip, Count, % ++x
AWK
BEGIN {
for( i=0; i != i + 1; i++ )
print( i )
}
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
.
Axe
Integers in Axe are limited to 16 bits, or a maximum of 65535. This script will run infinitely until either the variable overflows or a key is pressed.
While getKey(0)
End
0→I
Repeat getKey(0)
Disp I▶Dec,i
I++
EndIf I=0
BASIC
10 LET A = 0
20 LET A = A + 1
30 PRINT A
40 GO TO 20
A = 0
DO: A = A + 1: PRINT A: LOOP 1
BASIC256
i = 1
do
print i
i += 1
until i = 0
Batch File
Variables are limited to 32bit integer, capable of a maximum value of 2,147,483,647
@echo off
set number=0
:loop
set /a number+=1
echo %number%
goto loop
- Output:
... 2147483644 2147483645 2147483646 2147483647 -2147483648 -2147483647 -2147483646 -2147483645 ...
BBC BASIC
Native version, limited to 53-bit integers (maximum output 9007199254740992):
*FLOAT 64
REPEAT
i += 1
PRINT TAB(0,0) i;
UNTIL FALSE
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):
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
bc
while (++i) i
beeswax
Using an ordinary loop structure:
qNP<
_1>{d
Using a jump instruction:
_1F6~@{PN@J
Numbers in beeswax are unsigned 64-bit integers, so after reaching 2^64-1 the counter wraps around to 0.
Befunge
The range of a numeric value in Befunge is implementation dependent, but is commonly 32 bit signed integers for the stack, so a maximum value of 2147483647. However, note that some implementations have a smaller range for displayed values, so the sequence may appear to wrap to negative numbers while the internal value is in fact still increasing.
Also note that the range of values written to the code page or 'playfield' is often much smaller - frequently only supporting 8 bits, sometimes signed, sometimes unsigned.
1+:0`!#@_:.55+,
BQN
While the input is lesser than or equal to infinity, print, then increment.
_while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
(1+•Show) _while_ (≤⟜∞) 1
Bracmat
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.
0:?n&whl'out$(1+!n:?n)
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.
++++++++++>>>+[[->>+<[+>->+<<---------------------------------------
-------------------[>>-<++++++++++<[+>-<]]>[-<+>]<++++++++++++++++++
++++++++++++++++++++++++++++++>]<[<]>>[-<+++++++++++++++++++++++++++
++++++++++++++++++++++>]>]>[>>>]<<<[.<<<]<.>>>+]
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.
++++++++++>>-[>+[->>+<[+>->+<<--------------------------------------
--------------------[>>-<++++++++++<[+>-<]]>[-<+>]<+++++++++++++++++
+++++++++++++++++++++++++++++++>]<[<]>>[-<++++++++++++++++++++++++++
+++++++++++++++++++++++>]>]>[>>>]<<<[.<<<]<.>>-]
This program can count in any base counting system under 256. Note: Change the characters in quotes equal to the base counting system you want to use.
+[<<+>>[[<<"-----------"["+++++++++++"<]>]>[<<<<+>>+>>[>>]<]<]>>[>>]<<]
Brat
i = 1
loop {
p i
i = i + 1
}
Burlesque
1R@
C
Prints from 1 to max unsigned integer (usually 2**32 -1), then stops.
#include <stdio.h>
int main()
{
unsigned int i = 0;
while (++i) printf("%u\n", i);
return 0;
}
This one never stops. It's not even likely that you'll run out of memory before you run out of patience.
#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;
}
OpenSSL provides arbitrarily large integers.
#include <openssl/bn.h> /* BN_*() */
#include <openssl/err.h> /* ERR_*() */
#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 */
}
C#
using System;
using System.Numerics;
class Program
{
static void Main()
{
BigInteger i = 1;
while (true)
{
Console.WriteLine(i++);
}
}
}
C++
#include <cstdint>
#include <iostream>
#include <limits>
int main()
{
auto i = std::uintmax_t{};
while (i < std::numeric_limits<decltype(i)>::max())
std::cout << ++i << '\n';
}
ChucK
Math.INT_MAX is a constant value that represents the greater integer, 32 bit , 64 bit systems.
for(1 => int i; i < Math.INT_MAX; i ++)
{
<<< i >>>;
}
Clean
In Clean this example has a limit of basically 2147483648.
module IntegerSequence
import StdEnv
Start = [x \\ x <- [1..]]
Output:
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,..
Clojure
(map println (next (range)))
CLU
% This iterator will generate all integers until the built-in type
% overflows. It is a signed machine-sized integer; so 64 bits on
% a modern machine. After that it will raise an exception.
to_infinity_and_beyond = iter () yields (int)
i: int := 0
while true do
i := i + 1
yield(i)
end
end to_infinity_and_beyond
start_up = proc ()
po: stream := stream$primary_output()
for i: int in to_infinity_and_beyond() do
stream$putl(po, int$unparse(i))
end
end start_up
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
.
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.
# This very limited BCD-based collection of functions
# makes it easy to count very large numbers. All arrays
# start off with the ones columns in position zero.
# Using arrays of decimal-based digits to model integers
# doesn't make much sense for most tasks, but if you
# 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
# 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
output
> coffee foo.coffee | head -5
199999999999999999999999999999999999999999999999999999
200000000000000000000000000000000000000000000000000000
200000000000000000000000000000000000000000000000000001
200000000000000000000000000000000000000000000000000002
200000000000000000000000000000000000000000000000000003
Common Lisp
(loop for i from 1 do (print i))
If your compiler does tail call elimination (note: this has absolutely no advantage over normal loops):
(defun pp (x) (pp (1+ (print x))))
(funcall (compile 'pp) 1) ; it's less likely interpreted mode will eliminate tails
Component Pascal
BlackBox Component Builder
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.
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 ...
Computer/zero Assembly
This program counts up to 255 in the accumulator, after which it starts again from zero.
start: ADD one
JMP start
one: 1
Cowgol
The largest integer type that Cowgol supports out of the box is the unsigned 32-bit integer. This program will count up to 2^32-1, and then stop.
include "cowgol.coh";
var n: uint32 := 1;
while n != 0 loop;
print_i32(n);
print_nl();
n := n + 1;
end loop;
The following program will keep going until it runs out of memory, using one byte per digit.
include "cowgol.coh";
sub print_back(s: [uint8]) is
while [s] != 0 loop;
print_char([s]);
s := @prev s;
end loop;
print_nl();
end sub;
sub incr(n: [uint8]): (r: [uint8]) is
r := n;
while [n] != 0 loop;
n := @prev n;
end loop;
n := @next n;
loop
if [n] == 0 then
[n] := '1';
[@next n] := 0;
r := n;
break;
elseif [n] == '9' then
[n] := '0';
n := @next n;
continue;
else
[n] := [n] + 1;
break;
end if;
end loop;
end sub;
sub init(n: [uint8]): (r: [uint8]) is
[n] := 0;
[n+1] := '0';
[n+2] := 0;
r := n+1;
end sub;
var infnum := init(LOMEM);
loop
infnum := incr(infnum);
print_back(infnum);
end loop;
Crystal
Will run as long as enough memory to represent numbers.
require "big"
(1.to_big_i ..).each { |i| puts i }
D
import std.stdio, std.bigint;
void main() {
BigInt i;
while (true)
writeln(++i);
}
Alternative:
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;
}
}
Dc
1[p1+lpx]dspx
DCL
$ i = 1
$ loop:
$ write sys$output i
$ i = i + 1
$ goto loop
- Output:
1 2 3 ... 2147483646 2147483647 -2147483648 -2147483647 ... -1 0 1 ...
Delphi
program IntegerSequence;
{$APPTYPE CONSOLE}
var
i: Integer;
begin
for i := 1 to High(i) do
WriteLn(i);
end.
DWScript
High(i) returns the maximum supported value, typically, it is the highest signed 64 bit integer.
var i: Integer;
for i:=1 to High(i) do
PrintLn(i);
Dyalect
var n = 0
while true {
n += 1
print(n)
}
Déjà Vu
1
while /= -- dup dup:
!. dup
++
drop
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.
E
for i in int > 0 { println(i) }
EasyLang
max = pow 2 53
repeat
print i
if i = 10
print "."
print "."
i = max - 10
.
until i = max
i += 1
.
EchoLisp
(lib 'bigint) ;; arbitrary length integers
(for ((n (in-naturals))) (writeln n))
EDSAC order code
[ Integer sequence
================
A program for the EDSAC
Displays integers 1,2,3...
in binary form in the first
word of storage tank 2
until stopped
Works with Initial Orders 2 ]
T56K [ set load point ]
GK [ set base address ]
A3@ [ increment accumulator ]
U64F [ copy accumulator to 64 ]
E@ [ jump to base address ]
P0D [ constant: 1 ]
EZPF [ begin at load point ]
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
Elena
ELENA 4.x :
import extensions;
public program()
{
var i := 0u;
while (true)
{
console.printLine(i);
i += 1u
}
}
Elixir
Stream.iterate(1, &(&1+1)) |> Enum.each(&(IO.puts &1))
Emacs Lisp
Displays in the message area interactively, or to standard output under -batch
.
(dotimes (i most-positive-fixnum)
(message "%d" (1+ i)))
Erlang
F = fun(FF, I) -> io:format("~p~n", [I]), FF(FF, I + 1) end, F(F,0).
ERRE
.............
A%=0
LOOP
A%=A%+1
PRINT(A%;)
END LOOP
.............
% is integer-type specificator. Integer type works on 16-bit signed numbers (reserved constant MAXINT is 32767). Beyond this limit execution will give Runtime error #6 (overflow).
Euphoria
integer i
i = 0
while 1 do
? i
i += 1
end while
F#
// lazy sequence of integers starting with i
let rec integers i =
seq { yield i
yield! integers (i+1) }
Seq.iter (printfn "%d") (integers 1)
lazy sequence of int32 starting from 0
let integers = Seq.initInfinite id
lazy sequence of int32 starting from n
let integers n = Seq.initInfinite ((+) n)
lazy sequence (not necessarily of int32) starting from n (using unfold anamorphism)
let inline numbers n =
Seq.unfold (fun n -> Some (n, n + LanguagePrimitives.GenericOne)) n
> 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
USE: lists.lazy
1 lfrom [ . ] leach
Fantom
class Main
{
public static Void main()
{
i := 1
while (true)
{
echo (i)
i += 1
}
}
}
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
Fermat
n:=0;
while 1 do !n;!' '; n:=n+1 od
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:
0>:n1+v
^o" "<
Forth
: ints ( -- )
0 begin 1+ dup cr u. dup -1 = until drop ;
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
FreeBASIC
' FB 1.05.0 Win64
' FB does not natively support arbitrarily large integers though support can be added
' by using an external library such as GMP. For now we will just use an unsigned integer (32bit).
Print "Press Ctrl + C to stop the program at any time"
Dim i As UInteger = 1
Do
Print i
i += 1
Loop Until i = 0 ' will wrap back to 0 when it reaches 4,294,967,296
Sleep
Frink
All of Frink's numbers can be arbitrarily-sized:
i=0
while true
{
println[i]
i = i + 1
}
FunL
The following has no limit since FunL has arbitrary size integers.
for i <- 1.. do println( i )
Futhark
Infinite loops cannot produce results in Futhark, so this program accepts an input indicating how many integers to generate. It encodes the size of the returned array in its type.
fun main(n: int): [n]int = iota n
FutureBasic
ULLONG_MAX = 18446744073709551615. So this will crash long before getting there!
include "NSLog.incl"
UInt64 i = 1
while ( i < ULLONG_MAX )
NSLog( @"%llu\n", i )
i++
wend
// NSLog( @"Maximum Unsigned long long: %llu", ULLONG_MAX )
HandleEvents
GAP
InfiniteLoop := function()
local n;
n := 1;
while true do
Display(n);
n := n + 1;
od;
end;
# Prepare some coffee
InfiniteLoop();
Go
Size of int type is implementation dependent. After the maximum positive value, it rolls over to maximum negative, without error. Type uint will roll over to zero.
package main
import "fmt"
func main() {
for i := 1;; i++ {
fmt.Println(i)
}
}
The big.Int 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.
package main
import (
"big"
"fmt"
)
func main() {
one := big.NewInt(1)
for i := big.NewInt(1);; i.Add(i, one) {
fmt.Println(i)
}
}
Gridscript
#INTEGER SEQUENCE.
@width
@height 1
(1,1):START
(3,1):STORE 1
(5,1):CHECKPOINT 0
(7,1):PRINT
(9,1):INCREMENT
(11,1):GOTO 0
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 }
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.
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]
GW-BASIC
10 A#=1
20 PRINT A#
30 A#=A#+1
40 GOTO 20
Haskell
mapM_ print [1..]
Or less imperatively:
putStr $ unlines $ map show [1..]
HolyC
Prints from 1 to max unsigned 64 bit integer (2**64 -1), then stops.
U64 i = 0;
while (++i) Print("%d\n", i);
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.
IS-BASIC
100 FOR I=1 TO INF
110 PRINT I;
120 NEXT
INF = 9.999999999E62
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.
count=: (echo ] >:)^:_
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).
count=: (echo ] >:)@x:^:_
Jakt
Jakt's default integer type is i64. Specifying 1u64 allows it to (theoretically) count to 2^64 - 2 (The range has an implicit exclusive upper bound of 2^64 - 1).
fn main() {
for i in (1u64..) {
println("{}", i)
}
}
Java
Long limit:
public class Count {
public static void main(String[] args) {
for(long i = 1; ;i++) System.out.println(i);
}
}
"Forever":
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);
}
}
This solution leverages the Stream API to create declarative integer sequences, which is arguably more readable than the unbound for loop approach.
Overflow-unsafe code using the long primitive:
import java.util.stream.LongStream;
public class Count {
public static void main(String[] args) {
LongStream.iterate(1, l -> l + 1)
.forEach(System.out::println);
}
}
BigInteger solution with arbitrary size integers:
import static java.math.BigInteger.ONE;
import java.util.stream.Stream;
public class Count {
public static void main(String[] args) {
Stream.iterate(ONE, i -> i.add(ONE))
.forEach(System.out::println);
}
}
JavaScript
This code is accurate up to 2^53 where it will be stuck an 2^53 because a IEEE 64-bit double can not represent 2^53 + 1.
var i = 0;
while (true)
document.write(++i + ' ');
This example uses a BigInt[1] literal to support arbitrary large integers.
var i = 0n;
while (true)
document.write(++i + ' ');
Joy
1 [0 >] [dup put succ] while pop.
Counting stops at maxint
: 2147483647
jq
The Go implementation of jq does support arbitrary-precision integer arithmetic, but currently (2024) the C implementation of jq will resort to floating-point arithmetic for very large integers.
Consider, for example:
0 | recurse(. + 1)
Using gojq, this will indefinitely generate a stream of integers beginning with 0, but jq (the C implementation) will eventually lose precision.
For generating integers, the built-in function range(m;n) is more likely to be useful in practice; if m and n are integers, it generates integers from m to n-1, inclusive. `range(m; infinite)` is also valid for any integer.
The C implementation of jq supports tail recursion optimization, and thus the following tail-recursive definition could be used:
def iota: ., (. + 1 | iota);
0 | iota
One could also write:
0 | while(true; . + 1)
Integers can of course also be represented by strings of decimal digits, and if this representation is satisfactory, a stream of consecutive integers thus represented can be generated using the same technique as is employed on the Count_in_octal page.
Julia
i = zero(BigInt) # or i = big(0)
while true
println(i += 1)
end
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
{`0:"\n",$x+:1;x}/1
Using a while
loop:
i:0; while[1;`0:"\n",$i+:1]
Kotlin
import java.math.BigInteger
fun main() {
// Using a 64-bit unsigned type, print until 18446744073709551615
(1u..ULong.MAX_VALUE).forEach { println(it) }
// Using unlimited-size integers, print forever
var n = BigInteger.ONE
while (true) println(n++)
}
Lambdatalk
The long_add primitive allow counting beyond the javascript numbers limits, depending on the system memory.
{def infinite_set
{lambda {:i}
{if true // will never change
then :i {infinite_set {long_add :i 1}} // extends {+ :i 1}
else You have reached infinity! }}} // probably never.
-> infinite_set
{infinite_set 0}
-> 0 1 2 3 ... forever
Lang
# LONG limit (64 bits signed)
$l = 1L
loop {
fn.println($l)
$l += 1
}
Lang5
0 do dup . 1 + loop
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
^}
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.
while 1
i=i+1
locate 1,1
print i
scan
wend
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:
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);
}
}
Lingo
i = 1
repeat while i>0
put i
i = i+1
end repeat
Lingo uses signed 32 bit integers, so max. supported integer value is 2147483647:
put the maxInteger
-- 2147483647
Beyond this limit values behave like negative numbers:
put the maxInteger+1
-- -2147483648
put the maxInteger+2
-- -2147483647
Up to the (quite high) number where floats (double-precission) start rounding, floats can be used to exceed the integer limit:
the floatPrecision = 0 -- forces floats to be printed without fractional digits
put float(the maxInteger)+1
-- 2147483648
-- max. whole value that can be stored as 8-byte-float precisely
maxFloat = power(2,53) -- 9007199254740992.0
i = 1.0
repeat while i<=maxFloat
put i
i = i+1
end repeat
-- 1
-- 2
-- 3
-- ...
LLVM
; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps
;--- The declarations for the external C functions
declare i32 @printf(i8*, ...)
$"FORMAT_STR" = comdat any
@"FORMAT_STR" = linkonce_odr unnamed_addr constant [4 x i8] c"%u\0A\00", comdat, align 1
; Function Attrs: noinline nounwind optnone uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4 ;-- allocate i
store i32 0, i32* %1, align 4 ;-- store i as 0
br label %loop
loop:
%2 = load i32, i32* %1, align 4 ;-- load i
%3 = add i32 %2, 1 ;-- increment i
store i32 %3, i32* %1, align 4 ;-- store i
%4 = icmp ne i32 %3, 0 ;-- i != 0
br i1 %4, label %loop_body, label %exit
loop_body:
%5 = load i32, i32* %1, align 4 ;-- load i
%6 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"FORMAT_STR", i32 0, i32 0), i32 %5)
br label %loop
exit:
ret i32 0
}
attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
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
M2000 Interpreter
\\ easy way
a=1@
\\ Def statement defines one time (second pass produce error)
Rem : Def Decimal a=1
Rem : Def a as decimal=1
\\ Global shadow any global with same name, but not local
\\ globals can change type, local can't change
\\ to assign value to global need <=
\\ Symbol = always make local variables (and shadows globals)
Rem : Global a as decimal =1
\\Local make a new local and shadow one with same name
Rem : Local a as decimal=1
\\ we can create an "auto rounding" variable
\\ an integer with any type (double, single, decimal, currency, long, integer)
\\ rounding to .5 : up for positive numbers and down to negative
\\ 1.5 round to 2 and -1.5 round to -2
a%=1@
\\ variables a, a%, a$, arrays/functions a(), a$(), sub a() and the module a can exist together
\\ A block may act as loop structure using an internal flag
\\ A Loop statement mark a flag in the block, so can be anywhere inside,
\\ this flag reset to false before restart.
{loop : Print a : a++}
Maple
Maple has arbitrary-precision integers so there are no built-in limits on the size of the integers represented.
for n do
print(n)
end do;
Mathematica / Wolfram Language
Built in arbitrary precision support means the following will not overflow.
x = 1;
Monitor[While[True, x++], x]
MATLAB / Octave
a = 1; while (1) printf('%i\n',a); a=a+1; end;
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
a = uint64(1); while (1) printf('%i\n',a); a=a+1; end;
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.
N = 2^30; printf('%d\n', 1:N);
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
for i do disp(i);
min
min's integers are 64-bit signed. This will eventually overflow.
0 (dup) () (puts succ) () linrec
МК-61/52
1 П4 ИП4 С/П КИП4 БП 02
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
Modula-2
MODULE Sequence;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
VAR
buf : ARRAY[0..63] OF CHAR;
i : CARDINAL;
BEGIN
i := 1;
WHILE i>0 DO
FormatString("%c ", buf, i);
WriteString(buf);
INC(i)
END;
ReadChar
END Sequence.
Nanoquery
All native integers in Nanoquery can become arbitrarily large by default, so this program would run until it ran out of memory.
i = 1
while true
println i
i += 1
end
Necromantus
In Necromantus integer size is limited by the java's int.
let i = 0;
while true
{
write(i);
i = i + 1;
}
NetRexx
Rexx Built In
NetRexx provides built-in support for very large precision arithmetic via the Rexx class.
/* 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_
Using BigInteger
Java's BigInteger class is also available for very large precision arithmetic.
/* 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
NewLISP
(while (println (++ i)))
Nim
var i:int64 = 0
while true:
inc i
echo i
Using BigInts:
import bigints
var i = 0.initBigInt
while true:
i += 1
echo i
Nu
for n in 1.. { print $n }
Oberon-2
Works with oo2c Version 2
MODULE IntegerSeq;
IMPORT
Out,
Object:BigInt;
PROCEDURE IntegerSequence*;
VAR
i: LONGINT;
BEGIN
FOR i := 0 TO MAX(LONGINT) DO
Out.LongInt(i,0);Out.String(", ")
END;
Out.Ln
END IntegerSequence;
PROCEDURE BigIntSequence*;
VAR
i: BigInt.BigInt;
BEGIN
i := BigInt.zero;
LOOP
Out.Object(i.ToString() + ", ");
i := i.Add(BigInt.one);
END
END BigIntSequence;
END IntegerSeq.
Objeck
bundle Default {
class Count {
function : Main(args : String[]) ~ Nil {
i := 0;
do {
i->PrintLine();
i += 1;
} while(i <> 0);
}
}
}
OCaml
with an imperative style:
let () =
let i = ref 0 in
while true do
print_int !i;
print_newline ();
incr i;
done
with a functional style:
let () =
let rec aux i =
print_int i;
print_newline ();
aux (succ i)
in
aux 0
Oforth
Oforth handles arbitrary integer precision.
The loop will stop when out of memory
: integers 1 while( true ) [ dup . 1+ ] ;
Ol
Ol does not limit the size of numbers. So maximal number depends only on available system memory.
(let loop ((n 1))
(print n)
(loop (+ 1 n)))
Sample sequence with break for large numbers:
(let loop ((n 2))
(print n)
(unless (> n 100000000000000000000000000000000)
(loop (* n n))))
Output:
2 4 16 256 65536 4294967296 18446744073709551616 340282366920938463463374607431768211456
OpenEdge/Progress
OpenEdge has three data types that can be used for this task:
- INTEGER (32-bit signed integer)
DEF VAR ii AS INTEGER FORMAT "->>>>>>>>9" NO-UNDO. DO WHILE TRUE: ii = ii + 1. DISPLAY ii. END.
When an integer rolls over its maximum of 2147483647 error 15747 is raised (Value # too large to fit in INTEGER.).
- INT64 (64-bit signed integer)
DEF VAR ii AS INT64 FORMAT "->>>>>>>>>>>>>>>>>>9" NO-UNDO. DO WHILE TRUE: ii = ii + 1. DISPLAY ii. END.
When a 64-bit integer overflows no error is raised and the signed integer becomes negative.
- DECIMAL (50 digits)
DEF VAR de AS DECIMAL FORMAT "->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>9" NO-UNDO. DO WHILE TRUE: de = de + 1. DISPLAY de. END.
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:
#include <order/interpreter.h>
#define ORDER_PP_DEF_8printloop ORDER_PP_FN( \
8fn(8N, \
8do(8print(8to_lit(8N) 8comma 8space), \
8printloop(8inc(8N)))) )
ORDER_PP( 8printloop(1) )
... 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:
#include <order/interpreter.h>
#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,
PARI/GP
n=0; while(1,print(++n))
Pascal
See also Delphi
Quad word has the largest positive range of all ordinal types
Program IntegerSequenceLimited;
var
Number: QWord = 0; // 8 bytes, unsigned: 0 .. 18446744073709551615
begin
repeat
writeln(Number);
inc(Number);
until false;
end.
With the gmp library your patience is probably the limit :-)
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.
PascalABC.NET
Uses functionality from Fibonacci n-step number sequences#PascalABC.NET
// Integer sequence. Nigel Galloway: September 8th., 2022
function initInfinite(start: integer):=unfold(n->(n,n+1),start);
function initInfinite(start: biginteger):=unfold(n->(n,n+1),start);
begin
initInfinite(23).Take(10).Println;
initInfinite(-3).Take(10).Println;
initInfinite(2bi**70).Take(10).Println;
end.
- Output:
23 24 25 26 27 28 29 30 31 32 -3 -2 -1 0 1 2 3 4 5 6 1180591620717411303424 1180591620717411303425 1180591620717411303426 1180591620717411303427 1180591620717411303428 1180591620717411303429 1180591620717411303430 1180591620717411303431 1180591620717411303432 1180591620717411303433
Example 2.
## 1.Step.Print
- 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 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 ...
Perl
my $i = 0;
print ++$i, "\n" while 1;
On 64-bit Perls this will get to 2^64-1 then print 1.84467440737096e+19 forever. On 32-bit Perls using standard doubles this will get to 999999999999999 then start incrementing and printing floats until they lose precision. This behavior can be changed by adding something like:
use bigint;
my $i = 0; print ++$i, "\n" while 1;
which makes almost all integers large (ranges are excluded). Faster alternatives exist with non-core modules, e.g.
- use bigint lib=>"GMP";
- use Math::Pari qw/:int/;
- use Math::GMP qw/:constant/;
Phix
This will crash at 1,073,741,824 on 32 bit, or 4,611,686,018,427,387,904 on 64-bit, and as indicated best not to try this or any below under pwa/p2js:
without javascript_semantics integer i = 0 while 1 do ?i i += 1 end while
This will stall at 9,007,199,254,740,992 on 32-bit, and about twice the above on 64-bit. (after ~15 or 19 digits of precision, adding 1 will simply cease to have any effect)
without javascript_semantics atom a = 0 while 1 do ?a a += 1 end while
This will probably carry on until the number has over 300 million digits (32-bit, you can square that on 64-bit) which would probably take zillions of times longer than the universe has already existed, if your hardware/OS/power grid kept going that long.
without javascript_semantics include mpfr.e mpz b = mpz_init(0) while true do mpz_add_ui(b,b,1) mpfr_printf(1,"%Zd\n",b) end while
Lastly, a gui version you can run online here.
with javascript_semantics include pGUI.e include mpfr.e Ihandln dlg, lbl mpz i = mpz_init(0) function increment() mpz_add_ui(i,i,1) IupSetStrAttribute(lbl,"TITLE",mpz_get_str(i)) return IUP_DEFAULT end function IupOpen() lbl = IupLabel("","PADDING=10x10,EXPAND=YES") dlg = IupDialog(lbl, "TITLE=Integers,SIZE=160x50") IupShow(dlg) IupSetGlobalFunction("IDLE_ACTION",Icallback("increment")) if platform()!=JS then IupMainLoop() dlg = IupDestroy(dlg) IupClose() end if
PicoLisp
(for (I 1 T (inc I))
(printsp I) )
Piet
Rendered as a Wiki table because uploading images is not possible.
ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww |
ww | ww | ww | ww | ww | ww | ww |
Program explanation on my user page: [2]
Pike
int i=1;
while(true)
write("%d\n", i++);
PILOT
C :n = 1
*InfiniteLoop
T :#n
C :n = n + 1
J :*InfiniteLoop
PL/I
infinity: procedure options (main);
declare k fixed decimal (30);
put skip edit
((k do k = 1 to 999999999999999999999999999998))(f(31));
end infinity;
PL/M
PL/M natively supports two integer types, named BYTE
and ADDRESS
.
ADDRESS
is a 16-bit integer, so it can count up to 65536. The following program
will print numbers until the ADDRESS
variable overflows.
100H:
/* CP/M CALL AND NUMBER OUTPUT ROUTINE */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PRINT: PROCEDURE (STR);
DECLARE STR ADDRESS;
CALL BDOS(9, STR);
END PRINT;
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P - 1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUMBER;
/* PRINT NUMBERS UNTIL ADDRESS VARIABLE OVERFLOWS */
DECLARE N ADDRESS INITIAL (1);
DO WHILE N <> 0;
CALL PRINT$NUMBER(N);
N = N + 1;
END;
CALL BDOS(0,0);
EOF
To get around this limitation, the following program stores the number as an array of digits. It will keep going until it runs out of memory (and then it will crash). On a 64K CP/M system it will keep going until it has over 50.000 digits.
100H:
/* CP/M CALL */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
PUT$CHAR: PROCEDURE (CHAR);
DECLARE CHAR BYTE;
CALL BDOS(2, CHAR);
END PUT$CHAR;
/* PRINT STRING BACKWARDS UNTIL ZERO */
PRINT$BACK: PROCEDURE (S);
DECLARE S ADDRESS, C BASED S BYTE;
DO WHILE C <> 0;
CALL PUT$CHAR(C);
S = S - 1;
END;
CALL PUT$CHAR(13);
CALL PUT$CHAR(10);
END PRINT$BACK;
/* INCREMENT NUMBER STORED AS ASCII DIGITS */
INCR$BIGINT: PROCEDURE (BI) ADDRESS;
DECLARE (BI, R) ADDRESS, D BASED BI BYTE;
R = BI;
DO WHILE D <> 0; BI = BI - 1; END;
INCR$DIGIT:
BI = BI + 1;
IF D = 0 THEN DO;
D = '1';
D(1) = 0;
RETURN BI;
END;
ELSE IF D = '9' THEN DO;
D = '0';
GO TO INCR$DIGIT;
END;
ELSE DO;
D = D + 1;
RETURN R;
END;
END INCR$BIGINT;
/* STORE INITIAL 'BIG INTEGER' */
INIT$BIGINT: PROCEDURE (X) ADDRESS;
DECLARE X ADDRESS, D BASED X BYTE;
D(0) = 0;
D(1) = '0';
D(2) = 0;
RETURN .D(1);
END INIT$BIGINT;
/* LOOP PRINTING NUMBERS FOREVER */
DECLARE I ADDRESS;
I = INIT$BIGINT(.MEMORY);
DO WHILE 1;
I = INCR$BIGINT(I);
CALL PRINT$BACK(I);
END;
EOF
Plain English
Numbers are signed 32-bit values, so this will overflow somewhere in the neighborhood of 2.1 billion.
To run:
Start up.
Put 1 into a number.
Loop.
Convert the number to a string.
Write the string to the console.
Bump the number.
Repeat.
Shut down.
PostScript
1 {succ dup =} loop
PowerShell
try
{
for ([int]$i = 0;;$i++)
{
$i
}
}
catch {break}
Prolog
loop(I) :-
writeln(I),
I1 is I+1,
loop(I1).
Constraint Handling Rules
Works with SWI-Prolog and library CHR written by Tom Schrijvers and Jan Wielemaker
:- use_module(library(chr)).
:- chr_constraint loop/1.
loop(N) <=> writeln(N), N1 is N+1, loop(N1).
PureBasic
OpenConsole()
Repeat
a.q+1
PrintN(Str(a))
ForEver
Python
i=1
while i:
print(i)
i += 1
Or, alternatively:
from itertools import count
for i in count():
print(i)
Pythons integers are of arbitrary large precision and so programs would probably keep going until OS or hardware system failure.
QB64
Const iMax = 32767, UiMax = 65535
Const lMax = 2147483647, UlMax = 4294967295
Const iQBMax = 9223372036854775807, UiQBMax = 1844674407309551615
Dim iNum As _Integer64, iCount As _Integer64
Dim sChoice As String, sUnsigned As String, sQuit As String
Do While sChoice <> "I" And sChoice <> "L" And sChoice <> "6"
Input "Please choice among (I)nteger, (L)ong and Integer(6)4 ", sChoice
sChoice = UCase$(sChoice)
Loop
Do While sUnsigned <> "u" And sUnsigned <> "n"
Input "Please choice (U)nsigned or (N)ormal? ", sUnsigned
sUnsigned = LCase$(sUnsigned)
Loop
If sChoice = "I" Then
If sUnsigned = "n" Then iNum = iMax Else iNum = UiMax
ElseIf sChoice = "L" Then
If sUnsigned = "n" Then iNum = lMax Else iNum = UlMax
ElseIf sChoice = "6" Then
If sUnsigned = "n" Then iNum = iQBMax Else iNum = UiQBMax
End If
For iCount = 0 To iNum Step 1
Print iCount; " Press spacebar to exit "
sQuit = InKey$
Next
End
Q
Using converge (the \ adverb):
({-1 string x; x+1}\) 1
Using while:
i:0; while[1;-1 string (i+:1)]
Quackery
Quackery uses bignums.
0 [ 1+ dup echo cr again ]
R
z <- 0
repeat {
print(z)
z <- z + 1
}
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
(for ([i (in-naturals)]) (displayln i))
Raku
(formerly Perl 6)
.say for 1..*
Rapira
i := 1
while i do
output: i
i := i + 1
od
Raven
Raven uses signed 32 bit integer values.
1 as $i
repeat TRUE while
$i "%d\n" print $i 1000 + as $i
Red
Red ["Integer sequence"]
i: 1
forever [
print i
i: i + 1
]
Retro
Retro uses signed integer values.
#0 [ [ n:put spa ] sip n:inc dup n:-zero? ] while drop
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 Arthur Eddington in 1938 at his Tamer Lecture at │
│ Trinity College (Cambridge), he postulated that there are exactly │
│ │
│ 136 ∙ 2^256 │
│ │
│ protons in the universe and the same number of electrons, which is │
│ equal to around 1.57477e+79. │
│ │
│ Although, a modern estimate 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.*/
Ring
size = 10
for n = 1 to size
see n + nl
next
see nl
for n in [1:size]
see n + nl
next
see nl
i = n
while n <= size
see n + nl
n = n + 1
end
RPL
RPL code | Comment |
---|---|
≪ 64 STWS #1 DO DUP 1 DISP 1 + UNTIL #0 == END CLLCD ≫ 'COUNT' STO |
COUNT ( -- ) set integer size to 64 bits Initialize counter and loop display counter at top of screen increment Exit when 2^64-1 has been displayed |
Ruby
1.step{|n| puts n}
The step method of Numeric takes two optional arguments. The limit defaults to infinity, the step size to 1. Ruby does not limit the size of integers.
Ruby 2.6 introduced open-ended ranges:
(1..).each{|n| puts n}
Run BASIC
while 1
i = i + 1
print i
wend
Eventually as it gets larger it becomes a floating point.
Rust
fn main() {
for i in 0.. {
println!("{}", i);
}
}
Looping endlessly:
extern crate num;
use num::bigint::BigUint;
use num::traits::{One,Zero};
fn main() {
let mut i: BigUint = BigUint::one();
loop {
println!("{}", i);
i = i + BigUint::one();
}
}
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).
iterate (i; [0...+oo])
i!;
or
for (i; 0; true)
i!;
or
variable i := 0;
while (true)
{
i!;
++i;
};
Scala
Stream from 1 foreach println
Scheme
(let loop ((i 1))
(display i) (newline)
(loop (+ 1 i)))
Scheme does not limit the size of numbers.
sed
This program expects one line (consisting of a non-negative decimal integer) as start value:
:l
p
s/^9*$/0&/
h
y/0123456789/1234567890/
x
G
s/.9*\n.*\([^0]\)/\1/
bl
- Output:
$ echo 1 | sed -f count_dec.sed | head 1 2 3 4 5 6 7 8 9 10
Seed7
Limit 2147483647:
$ 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;
"Forever":
$ 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;
Sidef
No limit:
1..Inf -> each {.say}
Smalltalk
i := 0.
[
Stdout print:i; cr.
i := i + 1
] loop
will run forever.
SSEM
Since we have no Add instruction, we subtract -1 on each iteration instead of adding 1. The same -1 also serves as a jump target, taking advantage of a quirk of the SSEM architecture (the Current Instruction counter is incremented after the instruction has been executed, not before—so GOTO address has to be coded as GOTO address - 1).
01000000000000010000000000000000 0. Sub. 2 acc -= -1
01000000000000000000000000000000 1. 2 to CI goto -1 + 1
11111111111111111111111111111111 2. -1
Standard ML
This will print up to Int.maxInt and then raise an Overflow exception. On a 32 bit machine the max is 1073741823. Alternatively you could use Int64.int (64 bit) or IntInf.int (arbitrary precision).
let
fun printInts(n) =
(
print(Int.toString(n) ^ "\n");
printInts(n+1)
)
in
printInts(1)
end;
- Output:
1 2 3 ... 1073741821 1073741822 1073741823 uncaught exception Overflow [overflow] raised at: <file intSeq.sml>
SuperCollider
The SuperCollider language has a 32-bit signed int, and a 64 bit signed float. Instead of locking the interpreter with an infinite loop, we post the values over time.
i = Routine { inf.do { |i| i.yield } }; // return all integers, represented by a 64 bit signed float.
fork { inf.do { i.next.postln; 0.01.wait } }; // this prints them incrementally
A shorter form of the first line above, using list comprehensions:
i = {:i, i<-(0..) };
Swift
var i = 0
while true {
println(i++)
}
Symsyn
| The following code will run forever
| Symsyn uses a 64 bit signed integer
| The largest positive integer is 9223372036854775807
| lpi + 1 = -9223372036854775808
lp
x []
+ x
go lp
Tcl
package require Tcl 8.5
while true {puts [incr i]}
TI SR-56
Display | Key | Display | Key | Display | Key | Display | Key |
---|---|---|---|---|---|---|---|
00 84 | + | 25 | 50 | 75 | |||
01 01 | 1 | 26 | 51 | 76 | |||
02 94 | = | 27 | 52 | 77 | |||
03 59 | *pause | 28 | 53 | 78 | |||
04 42 | RST | 29 | 54 | 79 | |||
05 | 30 | 55 | 80 | ||||
06 | 31 | 56 | 81 | ||||
07 | 32 | 57 | 82 | ||||
08 | 33 | 58 | 83 | ||||
09 | 34 | 59 | 84 | ||||
10 | 35 | 60 | 85 | ||||
11 | 36 | 61 | 86 | ||||
12 | 37 | 62 | 87 | ||||
13 | 38 | 63 | 88 | ||||
14 | 39 | 64 | 89 | ||||
15 | 40 | 65 | 90 | ||||
16 | 41 | 66 | 91 | ||||
17 | 42 | 67 | 92 | ||||
18 | 43 | 68 | 93 | ||||
19 | 44 | 69 | 94 | ||||
20 | 45 | 70 | 95 | ||||
21 | 46 | 71 | 96 | ||||
22 | 47 | 72 | 97 | ||||
23 | 48 | 73 | 98 | ||||
24 | 49 | 74 | 99 |
Asterisk denotes 2nd function key.
0: Unused | 1: Unused | 2: Unused | 3: Unused | 4: Unused |
5: Unused | 6: Unused | 7: Unused | 8: Unused | 9: Unused |
Annotated listing:
+ 1 = // Increment the number
*pause // Flash the number on the display
RST // Loop
Usage:
Press CLR RST R/S. Incrementing numbers will flash on the screen. In one minute, the program counts to 86. Most of this time is taken displaying the number on the screen.
Note:
The minimum possible "Integer Sequence" program, which increments the number without displaying it, is:
+ 1 // Increment the number
RST // Loop
This program runs much faster. In one minute, the program counts to 640.
Tiny BASIC
REM will overflow after 32767
LET N = 0
10 PRINT N
LET N = N + 1
GOTO 10
True BASIC
LET i = 0
DO
PRINT i
LET i = i + 1
LOOP
END
TUSCRIPT
$$ MODE TUSCRIPT
LOOP n=0,999999999
n=n+1
ENDLOOP
Uiua
⍢(&p.+1)1 1
- Output:
Previous output truncated... 318259 318260 318261 318262 318263 318264 318265 318266 318267 318268 318269 318270 318271 318272 318273 318274 318275 318276 318277 318278 318279 318280 318281 318282 318283 318284 318285 318286 318287 318288 318289 318290 318291 318292 318293 318294 318295 318296 318297 318298 318299 318300 318301 318302 318303 318304 318305 318306 318307 318308 318309 318310 318311 318312 318313 318314 318315 You can increase the execution time limit in the editor settings
UNIX Shell
#!/bin/sh
num=0
while true; do
echo $num
num=`expr $num + 1`
done
Ursa
#
# integer sequence
#
# declare an int and loop until it overflows
decl int i
set i 1
while true
out i endl console
inc i
end while
Ursalang
let i = 1
loop {
print(i)
i := i + 1
}
Vala
uint i = 0;
while (++i < uint.MAX)
stdout.printf("%u\n", i);
Verilog
module main;
integer i;
initial begin
i = 1;
while(i > 0) begin
$display(i);
i = i + 1;
end
$finish ;
end
endmodule
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.")
For i As Integer = 0 To Integer.MaxValue
Console.WriteLine(i)
Next
Arbitrarily large numbers
One could use the System.Numerics library as the C# example did, or one can do the following.
A list of Long Integers is maintained as the incremented number. As the incremented value approaches the maximum allowed (base) in the first element of ar, a new item is inserted at the beginning of the list to extend the incremented number. The process has the limitation of when the ar array is enlarged to the point where the program exhausts the available memory, it ought to indicate failure and terminate. It is my understanding that a List count is backed by an Integer.MaxValue limitation and there may also be a 2 GB per object limitation involved. Since writing to the Console is such a slow process, I lack the patience to wait for the program (as written) to fail. If the program is tweaked to fail early, the practical limit seems to be a number 2,415,919,086 digits in length.
Imports System.Console
Module Module1
Dim base, b1 As Long, digits As Integer, sf As String, st As DateTime,
ar As List(Of Long) = {0L}.ToList, c As Integer = ar.Count - 1
Sub Increment(n As Integer)
If ar(n) < b1 Then
ar(n) += 1
Else
ar(n) = 0 : If n > 0 Then
Increment(n - 1)
Else
Try
ar.Insert(0, 1L) : c += 1
Catch ex As Exception
WriteLine("Failure when trying to increase beyond {0} digits", CDbl(c) * digits)
TimeStamp("error")
Stop
End Try
End If
End If
End Sub
Sub TimeStamp(cause As String)
With DateTime.Now - st
WriteLine("Terminated by {5} at {0} days, {1} hours, {2} minutes, {3}.{4} seconds",
.Days, .Hours, .Minutes, .Seconds, .Milliseconds, cause)
End With
End Sub
Sub Main(args As String())
digits = Long.MaxValue.ToString.Length - 1
base = CLng(Math.Pow(10, digits)) : b1 = base - 1
base = 10 : b1 = 9
sf = "{" & base.ToString.Replace("1", "0:") & "}"
st = DateTime.Now
While Not KeyAvailable
Increment(c) : Write(ar.First)
For Each item In ar.Skip(1) : Write(sf, item) : Next : WriteLine()
End While
TimeStamp("keypress")
End Sub
End Module
- Output:
1 2 3 ... 10267873 10267874 10267875 Terminated by keypress at 0 days, 0 hours, 30 minutes, 12.980 seconds
WDTE
let s => import 'stream';
s.new 0 (+ 1)
-> s.map (io.writeln io.stdout)
-> s.drain
;
WDTE's number type is, at the time of writing, backed by Go's float64
type, so all of the same limitations that apply there apply here. Also, this should not be run in the WDTE playground, as it will run with no output until the browser crashes or is killed.
Wren
In Wren all numbers are stored in 64-bit floating point form. This means that precise integer calculations are only possible within a maximum absolute magnitude of 2^53-1 (16 digits) unless one uses the Wren-big module whose BigInt class can deal with integers of arbitrary size.
Also, the System.print method in the standard library will only display a maximum of 14 digits before switching to scientific notation. To get around this one can use instead the Fmt.print method of the Wren-fmt module which displays integers 'normally' up to the maximum and also caters for BigInts as well.
import "./fmt" for Fmt
import "./big" for BigInt
var max = 2.pow(53) // 9007199254740992 (16 digits)
for (i in 1...max) Fmt.print("$d", i)
var bi = BigInt.new(max.toString)
while (true) {
Fmt.print("$i", bi)
bi = bi + 1
}
XBasic
PROGRAM "integseq"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
DO WHILE $$TRUE
INC i
PRINT i
LOOP
END FUNCTION
END PROGRAM
XLISP
(defun integer-sequence-from (x)
(print x)
(integer-sequence-from (+ x 1)) )
(integer-sequence-from 1)
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;
]
Yabasic
i = 1
repeat
print i
i = i + 1
until i = 0
end
Z80 Assembly
16-Bit
The Amstrad CPC's screen isn't big enough to show it all at once, but here you go. This prints numbers out (in hexadecimal) from 0x0001 to 0xFFFF.
org &1000
PrintChar equ &BB5A
ld hl,1 ;START AT ONE
main:
push hl
;PRINT HIGH BYTE
ld a,h
call ShowHex
;THEN PRINT LOW BYTE
ld a,l
call ShowHex
;NEW LINE
ld a,13
call PrintChar
ld a,10
call PrintChar
pop hl
;NEXT HL
inc hl
;COMPARE HL TO ZERO
ld a,h
or l
jr nz,main ;IF NOT ZERO, REPEAT
ret ;RETURN TO BASIC
ShowHex:
push af
and %11110000
rrca
rrca
rrca
rrca
call PrintHexChar
pop af
and %00001111
;call PrintHexChar
;execution flows into it naturally.
PrintHexChar:
;this converts hexadecimal to ascii.
or a ;Clear Carry Flag
daa
add a,&F0
adc a,&40
jp PrintChar
;ret
Arbitrarily Large Integers
This version displays an ever-increasing 64-bit unsigned integer. Unlike the previous version, this one continues forever and underflows to 0 after it reaches 0xFFFFFFFFFFFFFFFF. This logic can be extended to integers of up to 128 bytes in size (since IX+#
uses a signed offset, you'd need some way to alter the pointer to memory if you wanted even larger numbers than that, it's possible but a bit cumbersome. Not that this method wasn't cumbersome to begin with.)
org &1000
PrintChar equ &BB5A
ld ix,NumberRam
main:
ld a,(ix+7)
call ShowHex
ld a,(ix+6)
call ShowHex
ld a,(ix+5)
call ShowHex
ld a,(ix+4)
call ShowHex
ld a,(ix+3)
call ShowHex
ld a,(ix+2)
call ShowHex
ld a,(ix+1)
call ShowHex
ld a,(ix+0)
call ShowHex
;NEW LINE
ld a,13
call PrintChar
ld a,10
call PrintChar
ld a,(ix+0)
add 1 ;we can't just INC (ix+0) since that wouldn't affect the carry flag. So we have to add one to the value.
ld (ix+0),a
ld a,(ix+1)
adc 0 ;and carry it forward up to the max number of digits.
ld (ix+1),a
ld a,(ix+2)
adc 0
ld (ix+2),a
ld a,(ix+3)
adc 0
ld (ix+3),a
ld a,(ix+4)
adc 0
ld (ix+4),a
ld a,(ix+5)
adc 0
ld (ix+5),a
ld a,(ix+6)
adc 0
ld (ix+6),a
ld a,(ix+7)
adc 0
ld (ix+7),a
jp main
ret ;RETURN TO BASIC
ShowHex:
push af
and %11110000
rrca
rrca
rrca
rrca
call PrintHexChar
pop af
and %00001111
;call PrintHexChar
;execution flows into it naturally.
PrintHexChar:
;this converts hexadecimal to ascii.
or a ;Clear Carry Flag
daa
add a,&F0
adc a,&40
jp PrintChar
;ret
NumberRam: ;a 64-bit value, stored little-endian
db 01,00,00,00,00,00,00,00
Zig
const stdout = @import("std").io.getStdOut().writer();
pub fn main() !void {
var i: u128 = 1;
while (true) : (i += 1) {
try stdout.print("{}, ", .{i});
}
}
- Output:
... 324136, 324137, 324138, 324139, 324140, 324141, 324142, 324143, 324144, 324145, 324146, 324147, 324148, 324149, 324150, 324151, 324152, 324153, 324154, 324155, 324156, 324157, 324158, 324159, 324160, 324161, 324162, 324163, 324164, 324165, 324166, 324167, 324168, 324169, 324170, 324171, 324172, 324173, 324174, 324175, 324176, 324177, 324178, 324179, 324180, 324181, 324182, 324183, 324184, 324185, 324186, 324187, 324188, 324189, 324190, 324191,
zkl
[1..].pump(Console.println) // eager
m:=(1).MAX; [1..m].pump(Console.println) // (1).MAX is 9223372036854775807
[1..].pump(100,Console.println) // lazy