Integer sequence: Difference between revisions

From Rosetta Code
Content added Content deleted
(Better second D version)
(added OpenEdge solution)
Line 406: Line 406:
in
in
aux 0</lang>
aux 0</lang>

=={{header|OpenEdge/Progress}}==
OpenEdge has three data types that can be used for this task:
<ol><li>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.).
</li>
<li>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.
</li>
<li>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.).
</li>
</ol>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==

Revision as of 14:33, 24 July 2011

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.

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,...

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>

Brainf***

This program assumes the implementation prints out the integer equivalent of the cell value, as opposed to the character equivalent, and is thus implementation-dependent. In addition, since nearly all brainf*** implementations provide only a byte of memory space for each cell, and assuming the previous requirement is satisfied, only 1-255 will be displayed before overflow to 0 causes the loop to end. <lang brainf***>+[.+]</lang>

Brat

<lang brat>i = 1

while {

 p i
 i = i + 1

}</lang>

C

uint32_t has a range from 0 to 4294967295. After the program reaches 4294967295, it will overflow to 0.

<lang c>#include <stdio.h>

  1. include <stdint.h>

int main() {

 uint32_t i = 0;
 while (1)
 {
   printf("%u\n", ++i);
 }
 return 0;

}</lang>

Alternatively: <lang c>#include <stdio.h>

  1. include <stdint.h>

int main() {

 for (uint32_t i = 1; 1; i++)
   printf("%u\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) { unsigned long code;

fprintf(stderr, "%s: error\n", message); while (code = ERR_get_error()) fprintf(stderr, " %s\n", ERR_error_string(code, NULL)); 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>

Clojure

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

Common Lisp

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

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>

Delphi

<lang Delphi>program IntegerSequence;

{$APPTYPE CONSOLE}

var

 i: Integer;

begin

 while True do
 begin
   WriteLn(i);
   Inc(i);
 end;
 Readln;

end.</lang>

E

<lang e>for i in int > 0 { println(i) }</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>

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!

Forth

<lang forth>: ints 0 begin 1+ dup u. cr dup 0= 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>

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. <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>

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>

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>

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.).

PARI/GP

<lang parigp>n=0; while(1,print(++n))</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>

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.

Ruby

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

Ruby does not limit the size of numbers.

Scala

Works with: Scala version 2.8

<lang scala>def count(n:BigInt=0):Stream[BigInt]=n #:: count(n+1) count() 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.

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>

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>