Arbitrary-precision integers (included)

From Rosetta Code
Jump to: navigation, search
Task
Arbitrary-precision integers (included)
You are encouraged to solve this task according to the task description, using any language you may know.

Using the in-built capabilities of your language, calculate the integer value of:

5^{4^{3^2}}
  • Confirm that the first and last twenty digits of the answer are: 62060698786608744707...92256259918212890625
  • Find and show the number of decimal digits in the answer.

C.F. Long multiplication

Note:
  • Do not submit an implementation of arbitrary precision arithmetic. The intention is to show the capabilities of the language as supplied. If a language has a single, overwhelming, library of varied modules that is endorsed by its home site – such as CPAN for Perl or Boost for C++ – then that may be used instead.
  • Strictly speaking, this should not be solved by fixed-precision numeric libraries where the precision has to be manually set to a large value; although if this is the only recourse then it may be used with a note explaining that the precision must be set manually to a large enough value.
See also

Contents

[edit] ACL2

(in-package "ACL2")
 
(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
 
(set-print-length 0 state)
 
(defun arbitrary-precision ()
(declare (xargs :mode :program))
(let* ((x (expt 5 (expt 4 (expt 3 2))))
(s (mv-let (col str)
(fmt1-to-string "~xx"
(list (cons #\x x))
0)
(declare (ignore col))
str)))
(cw "~s0 ... ~x1 (~x2 digits)~%"
(subseq s 1 21)
(mod x (expt 10 20))
(1- (length s)))))
Output:
20606987866087447074 ... 92256259918212890625 (183231 digits)

[edit] Ada

Library: GMP
Using GMP, Ada bindings provided in GNATColl
with Ada.Text_IO; use Ada.Text_IO;
with GNATCOLL.GMP; use GNATCOLL.GMP;
with GNATCOLL.GMP.Integers; use GNATCOLL.GMP.Integers;
procedure ArbitraryInt is
type stracc is access String;
BigInt : Big_Integer;
len : Natural;
str : stracc;
begin
Set (BigInt, 5);
Raise_To_N (BigInt, Unsigned_Long (4**(3**2)));
str := new String'(Image (BigInt));
len := str'Length;
Put_Line ("Size is:"& Natural'Image (len));
Put_Line (str (1 .. 20) & "....." & str (len - 19 .. len));
end ArbitraryInt;
Output:
Size is: 183231
62060698786608744707.....92256259918212890625

[edit] Alore

def Main()
var len as Int
var result as Str
result = Str(5**4**3**2)
len = result.length()
Print(len)
Print(result[:20])
Print(result[len-20:])
end

[edit] bc

/* 5432.bc */
 
y = 5 ^ 4 ^ 3 ^ 2
c = length(y)
" First 20 digits: "; y / (10 ^ (c - 20))
" Last 20 digits: "; y % (10 ^ 20)
"Number of digits: "; c
quit
Output:
$ time bc 5432.bc  
 First 20 digits: 62060698786608744707
  Last 20 digits: 92256259918212890625
Number of digits: 183231
    0m24.81s real     0m24.81s user     0m0.00s system

[edit] Bracmat

At the prompt type the following one-liner:

{?} @(5^4^3^2:?first [20 ? [-21 ?last [?length)&str$(!first "..." !last "\nlength " !length)
{!} 62060698786608744707...92256259918212890625
length 183231
S 2,46 sec

[edit] C

[edit]
Library: GMP

#include <gmp.h>
#include <stdio.h>
#include <string.h>
 
int main()
{
mpz_t a;
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 1 << 18); /* 2**18 == 4**9 */
 
int len = mpz_sizeinbase(a, 10);
printf("GMP says size is: %d\n", len);
 
/* because GMP may report size 1 too big; see doc */
char *s = mpz_get_str(0, 10, a);
printf("size really is %d\n", len = strlen(s));
printf("Digits: %.20s...%s\n", s, s + len - 20);
 
// free(s); /* we could, but we won't. we are exiting anyway */
return 0;
}
Output:
GMP says size is: 183231
size really is 183231
Digits: 62060698786608744707...92256259918212890625

[edit]
Library: OpenSSL

OpenSSL is about 17 times slower than GMP (on one computer), but still fast enough for this small task.

/* 5432.c */
 
#include <openssl/bn.h> /* BN_*() */
#include <openssl/err.h> /* ERR_*() */
#include <stdlib.h> /* exit() */
#include <stdio.h> /* fprintf() */
#include <string.h> /* strlen() */
 
void
fail(const char *message)
{
fprintf(stderr, "%s: error 0x%08lx\n", ERR_get_error());
exit(1);
}
 
int
main()
{
BIGNUM two, three, four, five;
BIGNUM answer;
BN_CTX *context;
size_t length;
char *string;
 
context = BN_CTX_new();
if (context == NULL)
fail("BN_CTX_new");
 
/* answer = 5 ** 4 ** 3 ** 2 */
BN_init(&two);
BN_init(&three);
BN_init(&four);
BN_init(&five);
if (BN_set_word(&two, 2) == 0 ||
BN_set_word(&three, 3) == 0 ||
BN_set_word(&four, 4) == 0 ||
BN_set_word(&five, 5) == 0)
fail("BN_set_word");
BN_init(&answer);
if (BN_exp(&answer, &three, &two, context) == 0 ||
BN_exp(&answer, &four, &answer, context) == 0 ||
BN_exp(&answer, &five, &answer, context) == 0)
fail("BN_exp");
 
/* string = decimal answer */
string = BN_bn2dec(&answer);
if (string == NULL)
fail("BN_bn2dec");
 
length = strlen(string);
printf(" First 20 digits: %.20s\n", string);
if (length >= 20)
printf(" Last 20 digits: %.20s\n", string + length - 20);
printf("Number of digits: %zd\n", length);
 
OPENSSL_free(string);
BN_free(&answer);
BN_free(&five);
BN_free(&four);
BN_free(&three);
BN_free(&two);
BN_CTX_free(context);
 
return 0;
}
Output:
$ make LDLIBS=-lcrypto 5432 
cc -O2 -pipe    -o 5432 5432.c -lcrypto
$ time ./5432 
 First 20 digits: 62060698786608744707
  Last 20 digits: 92256259918212890625
Number of digits: 183231
    0m1.30s real     0m1.30s user     0m0.00s system

[edit] C#

System.Numerics.BigInteger was added in C# 4. The exponent of BigInteger.Pow() is limited to a 32-bit signed integer, which is not a problem in this specific task.

Works with: C# version 4+
using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
 
static class Program {
static void Main() {
BigInteger n = BigInteger.Pow(5, (int)BigInteger.Pow(4, (int)BigInteger.Pow(3, 2)));
string result = n.ToString();
 
Debug.Assert(result.Length == 183231);
Debug.Assert(result.StartsWith("62060698786608744707"));
Debug.Assert(result.EndsWith("92256259918212890625"));
 
Console.WriteLine("n = 5^4^3^2");
Console.WriteLine("n = {0}...{1}",
result.Substring(0, 20),
result.Substring(result.Length - 20, 20)
);
 
Console.WriteLine("n digits = {0}", result.Length);
}
}
Output:
n = 5^4^3^2
n = 62060698786608744707...92256259918212890625
n digits = 183231

[edit] Clojure

(defn exp [n k] (reduce * (repeat k n)))
 
(def big (->> 2 (exp 3) (exp 4) (exp 5)))
(def sbig (str big))
 
(assert (= "62060698786608744707" (.substring sbig 0 20)))
(assert (= "92256259918212890625" (.substring sbig (- (count sbig) 20))))
(println (count sbig) "digits")
 
(println (str (.substring sbig 0 20) ".."
(.substring sbig (- (count sbig) 20)))
(str "(" (count sbig) " digits)"))
Output:
output> 62060698786608744707..92256259918212890625 (183231 digits)

Redefining exp as follows speeds up the calculation of big about a hundred times:

(defn exp [n k]
(cond
(zero? (mod k 2)) (recur (* n n) (/ k 2))
(zero? (mod k 3)) (recur (* n n n) (/ k 3))
 :else (reduce * (repeat k n))))

[edit] Common Lisp

Common Lisp has arbitrary precision integers, inherited from MacLisp: "[B]ignums—arbitrary precision integer arithmetic—were added [to MacLisp] in 1970 or 1971 to meet the needs of Macsyma users." [Evolution of Lisp [1], 2.2.2]

(let ((s (format () "~s" (expt 5 (expt 4 (expt 3 2))))))
(format t "~a...~a, length ~a" (subseq s 0 20)
(subseq s (- (length s) 20)) (length s)))
Output:
62060698786608744707...92256259918212890625, length 183231

[edit] D

void main() {
import std.stdio, std.bigint, std.conv;
 
auto s = text(5.BigInt ^^ 4 ^^ 3 ^^ 2);
writefln("5^4^3^2 = %s..%s (%d digits)", s[0..20], s[$-20..$], s.length);
}
Output:
5^4^3^2 = 62060698786608744707..92256259918212890625 (183231 digits)

With dmd about 0.55 seconds compilation time (-release -noboundscheck) and about 3.3 seconds run time.

[edit] Dart

Dart's only integral type int supports arbitrary length integers.

void main() {
var s = pow(5, pow(4, pow(3, 2))).toString();
 
print('contains given digits: ${s.startsWith('62060698786608744707') && s.endsWith('92256259918212890625')}');
print('number of digits: ${s.length}');
}
Output:
contains given digits: true
number of digits: 183231

[edit] dc

Translation of: bc
[5432.dc]sz
 
5 4 3 2 ^ ^ ^ sy [y = 5 ^ 4 ^ 3 ^ 2]sz
ly Z sc [c = length of y]sz
[ First 20 digits: ]P ly 10 lc 20 - ^ / p sz [y / (10 ^ (c - 20))]sz
[ Last 20 digits: ]P ly 10 20 ^ % p sz [y % (10 ^ 20)]sz
[Number of digits: ]P lc p sz
Output:
$ time dc 5432.dc                                                              
 First 20 digits: 62060698786608744707
  Last 20 digits: 92256259918212890625
Number of digits: 183231
    0m24.80s real     0m24.81s user     0m0.00s system

[edit] E

E implementations are required to support arbitrary-size integers transparently.

? def value := 5**(4**(3**2)); null
? def decimal := value.toString(10); null
? decimal(0, 20)
# value: "62060698786608744707"
 
? decimal(decimal.size() - 20)
# value: "92256259918212890625"
 
? decimal.size()
# value: 183231

[edit] Emacs Lisp

Emacs Lisp has no big integers (bignums) in the language; but GNU Emacs 22 includes Calc, a library that implements big integers. The calc-eval function takes an algebraic formula in a string, and returns the result in a string.

Library: Calc
(let* ((answer (calc-eval "5**4**3**2"))
(length (length answer)))
(message "%s has %d digits"
(if (> length 40)
(format "%s...%s"
(substring answer 0 20)
(substring answer (- length 20) length))
answer)
length))

This implementation is very slow; one computer, running GNU Emacs 23.4.1, needed about seven minutes to find the answer.

Output:
62060698786608744707...92256259918212890625 has 183231 digits

[edit] Erlang

Erlang supports arbitrary precision integers. However, the math:pow function returns a float. This implementation includes an implementation of pow for integers with exponent greater than 0.

 
-module(arbitrary).
-compile([export_all]).
 
pow(B,E) when E > 0 ->
pow(B,E,1).
 
pow(_,0,_) -> 0;
pow(B,1,Acc) -> Acc * B;
pow(B,P,Acc) when P rem 2 == 0 ->
pow(B*B,P div 2, Acc);
pow(B,P,Acc) ->
pow(B,P-1,Acc*B).
 
test() ->
I = pow(5,pow(4,pow(3,2))),
[S] = io_lib:format("~b",[I]),
L = length(S),
Prefix = lists:sublist(S,20),
Suffix = lists:sublist(S,L-19,20),
io:format("Length: ~b~nPrefix:~s~nSuffix:~s~n",[L,Prefix,Suffix]).
 
Output:

23> arbitrary:test().

Length: 183231
Prefix:62060698786608744707
Suffix:92256259918212890625
ok

[edit] freebasic

freebasic has it's own gmp static library. Here, a power function operates via a string and uinteger.

 
 
 
#Include once "gmp.bi"
Dim Shared As Zstring * 100000000 outtext
 
Function Power(number As String,n As Uinteger) As String'automate precision
#define dp 3321921
Dim As __mpf_struct _number,FloatAnswer
Dim As Ulongint ln=Len(number)*(n)*4
If ln>dp Then ln=dp
mpf_init2(@FloatAnswer,ln)
mpf_init2(@_number,ln)
mpf_set_str(@_number,number,10)
mpf_pow_ui(@Floatanswer,@_number,n)
gmp_sprintf( @outtext,"%." & Str(n) & "Ff",@FloatAnswer )
Var outtxt=Trim(outtext)
If Instr(outtxt,".") Then outtxt= Rtrim(outtxt,"0"):outtxt=Rtrim(outtxt,".")
Return Trim(outtxt)
End Function
 
Extern gmp_version Alias "__gmp_version" As Zstring Ptr
Print "GMP version ";*gmp_version
Print
 
var ans=power("5",(4^(3^2)))
Print Left(ans,20) + " ... "+Right(ans,20)
Print "Number of digits ";Len(ans)
Sleep
 
GMP version 5.1.1

62060698786608744707 ... 92256259918212890625
Number of digits  183231

[edit] F#

You can specifiy arbitrary-precision integers (bigint or System.Numeric.BigInteger) in F# by postfixing the number with the letter 'I'. While '**' is the power function, two things should be noted:

  • bigint does not support raising to a power of a bigint
  • The int type does not support the power method
let () =
let answer = 5I **(int (4I ** (int (3I ** 2))))
let sans = answer.ToString()
printfn "Length = %d, digits %s ... %s" sans.Length (sans.Substring(0,20)) (sans.Substring(sans.Length-20))
;;
Length = 183231, digits 62060698786608744707 ... 92256259918212890625

[edit] Factor

Factor has built-in bignum support. Operations on integers overflow to bignums.

USING: formatting kernel math.functions math.parser sequences ;
IN: rosettacode.bignums
 
: test-bignums ( -- )
5 4 3 2 ^ ^ ^ number>string
[ 20 head ] [ 20 tail* ] [ length ] tri
"5^4^3^2 is %s...%s and has %d digits\n" printf ;

It prints: 5^4^3^2 is 62060698786608744707...92256259918212890625 and has 183231 digits

[edit] Frink

Frink has built-in arbitrary-precision integers and all operations automatically promote when necessary.

a = 5^4^3^2
as = "$a" // Coerce to string
println["Length=" + length[as] + ", " + left[as,20] + "..." + right[as,20]]

This prints Length=183231, 62060698786608744707...92256259918212890625

[edit] GAP

n:=5^(4^(3^2));; 
s := String(n);;
m := Length(s);
# 183231
s{[1..20]};
# "62060698786608744707"
s{[m-19..m]};
# "92256259918212890625"

[edit] Go

package main
 
import (
"fmt"
"math/big"
)
 
func main() {
answer := big.NewInt(42)
answer.Exp(big.NewInt(5), answer.Exp(big.NewInt(4),
answer.Exp(big.NewInt(3), big.NewInt(2), nil), nil), nil)
answer_string := answer.String()
length := len(answer_string)
fmt.Printf("has %d digits: %s ... %s\n",
length,
answer_string[0:20],
answer_string[length-20:])
}
Output:
has 183231 digits: 62060698786608744707 ... 92256259918212890625

[edit] Golfscript

5 4 3 2???  # Calculate 5^(4^(3^2))
`.. # Convert to string and make two copies
20<p # Print the first 20 digits
-20>p # Print the last 20 digits
,p # Print the length

The p command prints the top element from the stack, so the output of this program is just three lines:

"62060698786608744707"
"92256259918212890625"
183231

[edit] Groovy

Solution:

def bigNumber = 5G ** (4 ** (3 ** 2))

Test:

def bigString = bigNumber.toString()
 
assert bigString[0..<20] == "62060698786608744707"
assert bigString[-20..-1] == "92256259918212890625"
 
println bigString.size()
Output:
183231

[edit] Haskell

Haskell comes with built-in support for arbitrary precision integers. The type of arbitrary precision integers is Integer.

main = do
let y = show ( 5^4^3^2 )
let l = length y
putStrLn ("5**4**3**2 = " ++ take 20 y ++ "..." ++ drop (l-20) y ++ " and has " ++ show l ++ " digits")
Output:
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits

[edit] Icon and Unicon

Both Icon and Unicon have built-in support for bignums.

Note: It takes far longer to convert the result to a string than it does to do the computation itself.

procedure main()
x := 5^4^3^2
write("done with computation")
x := string(x)
write("5 ^ 4 ^ 3 ^ 2 has ",*x," digits")
write("The first twenty digits are ",x[1+:20])
write("The last twenty digits are ",x[0-:20])
end
Sample run:
->ap
done with computation
5 ^ 4 ^ 3 ^ 2 has 183231 digits
The first twenty digits are 62060698786608744707
The last twenty digits are  92256259918212890625
->

[edit] J

J has built-in support for extended precision integers. See also J:Essays/Extended Precision Functions.

   Pow5432=: 5^4^3^2x
Pow5432=: ^/ 5 4 3 2x NB. alternate J solution
# ": Pow5432 NB. number of digits
183231
20 ({. , '...' , -@[ {. ]) ": Pow5432 NB. 20 first & 20 last digits
62060698786608744707...92256259918212890625

[edit] Java

Java library's BigInteger class provides support for arbitrary precision integers.

import java.math.BigInteger;
 
class Program {
public static void main(String[] args) {
BigInteger x = BigInteger.valueOf(5).pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValue()).intValue());
String y = x.toString();
int l = y.length();
System.out.printf("5**4**3**2 = %s...%s and has %d digits\n",
y.substring(0,20), y.substring(l-20), l);
}
}
Output:
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits

[edit] Liberty BASIC

Interestingly this takes a LONG time in LB.

It takes however only seconds in RunBASIC, which is written by the same author, shares most of LB's syntax, and is based on later Smalltalk implementation.

Note the brackets are needed to enforce the desired order of exponentiating.

a$ = str$( 5^(4^(3^2))) 
print len( a$)
print left$( a$, 20); "......"; right$( a$, 20)
Output:
183231
62060698786608744707......92256259918212890625

[edit] Julia

Julia includes built-in support for arbitrary-precision arithmetic using the GMP (integer) and GNU MPFR (floating-point) libraries, wrapped by the built-in BigInt and BigFloat types, respectively.

julia> @elapsed bigstr = string(BigInt(5)^4^3^2)
0.017507363
 
julia> length(bigstr)
183231
 
julia> bigstr[1:20]
"62060698786608744707"
 
julia> bigstr[end-20:end]
"892256259918212890625"

[edit] Lasso

Interestingly, we have to define our own method for integer powers.

define integer->pow(factor::integer) => {
#factor <= 0
 ? return 0
 
local(retVal) = 1
 
loop(#factor) => { #retVal *= self }
 
return #retVal
}
 
local(bigint) = string(5->pow(4->pow(3->pow(2))))
#bigint->sub(1,20) + ` ... ` + #bigint->sub(#bigint->size - 19)
"\n"
`Number of digits: ` + #bigint->size
Output:
62060698786608744707 ... 92256259918212890625
Number of digits: 183231


[edit] Maple

Maple supports large integer arithmetic natively.

 
> n := 5^(4^(3^2)):
> length( n ); # number of digits
183231
 
> s := convert( n, 'string' ):
> s[ 1 .. 20 ], s[ -20 .. -1 ]; # extract first and last twenty digits
"62060698786608744707", "92256259918212890625"
 

In the Maple graphical user interface it is also possible to set things up so that only (say) the first and last 20 digits of a large integer are displayed explicitly. This is done as follows.

 
> interface( elisiondigitsbefore = 20, elisiondigitsafter = 20 ):
> 5^(4^(3^2)):
62060698786608744707[...183191 digits...]92256259918212890625
 

[edit] Mathematica

Mathematica can handle arbitrary precision integers on almost any size without further declarations. To view only the first and last twenty digits:

s:=ToString[5^4^3^2];
Print[StringTake[s,20]<>"..."<>StringTake[s,-20]<>" ("<>ToString@StringLength@s<>" digits)"];
Output:
62060698786608744707...92256259918212890625 (183231 digits)

[edit] MATLAB

Using the Variable Precision Integer library this task is accomplished thusly:

>> answer = vpi(5)^(vpi(4)^(vpi(3)^vpi(2)));
>> numDigits = order(answer) + 1
 
numDigits =
 
183231
 
>> [sprintf('%d',leadingdigit(answer,20)) '...' sprintf('%d',trailingdigit(answer,20))]
%First and Last 20 Digits
 
ans =
 
62060698786608744707...92256259918212890625

[edit] Maxima

block([s, n], s: string(5^4^3^2), n: slength(s), print(substring(s, 1, 21), "...", substring(s, n - 19)), n);
/* 62060698786608744707...92256259918212890625
183231 */

[edit] Nemerle

Translation of: C#
using System.Console;
using System.Numerics;
using System.Numerics.BigInteger;
 
module BigInt
{
Main() : void
{
def n = Pow(5, Pow(4, Pow(3, 2) :> int) :> int).ToString();
def len = n.Length;
def first20 = n.Substring(0, 20);
def last20 = n.Substring(len - 20, 20);
 
assert (first20 == "62060698786608744707", "High order digits are incorrect");
assert (last20 == "92256259918212890625", "Low order digits are incorrect");
assert (len == 183231, "Result contains wrong number of digits");
 
WriteLine("Result: {0} ... {1}", first20, last20);
WriteLine($"Length of result: $len digits");
}
}

Output:

Result: 62060698786608744707 ... 92256259918212890625
Length of result: 183231 digits

[edit] NetRexx

[edit] Using Java's BigInteger Class

/* NetRexx */
 
options replace format comments java crossref savelog symbols
 
import java.math.BigInteger
 
numeric digits 30 -- needed to report the run-time
 
nanoFactor = 10 ** 9
 
t1 = System.nanoTime
x = BigInteger.valueOf(5)
x = x.pow(BigInteger.valueOf(4).pow(BigInteger.valueOf(3).pow(2).intValue()).intValue())
n = Rexx(x.toString)
t2 = System.nanoTime
td = t2 - t1
say "Run time in seconds:" td / nanoFactor
say
 
check = "62060698786608744707...92256259918212890625"
sample = n.left(20)"..."n.right(20)
 
say "Expected result:" check
say " Actual result:" sample
say " digits:" n.length
say
 
if check = sample
then
say "Result confirmed"
else
say "Result does not satisfy test"
 
return
Output:
Run time in seconds: 6.696671 
 
Expected result: 62060698786608744707...92256259918212890625 
  Actual result: 62060698786608744707...92256259918212890625 
         digits: 183231 
 
Result confirmed

[edit] Using Java's BigDecimal Class

/* NetRexx */
 
options replace format comments java crossref savelog symbols
 
import java.math.BigDecimal
 
numeric digits 30 -- needed to report the run-time
 
nanoFactor = 10 ** 9
 
t1 = System.nanoTime
x = BigDecimal.valueOf(5)
x = x.pow(BigDecimal.valueOf(4).pow(BigDecimal.valueOf(3).pow(2).intValue()).intValue())
n = Rexx(x.toString)
t2 = System.nanoTime
td = t2 - t1
say "Run time in seconds:" td / nanoFactor
say
 
check = "62060698786608744707...92256259918212890625"
sample = n.left(20)"..."n.right(20)
 
say "Expected result:" check
say " Actual result:" sample
say " digits:" n.length
say
 
if check = sample
then
say "Result confirmed"
else
say "Result does not satisfy test"
 
return
Output:
Run time in seconds: 7.103424 
 
Expected result: 62060698786608744707...92256259918212890625 
  Actual result: 62060698786608744707...92256259918212890625 
         digits: 183231 
 
Result confirmed

[edit] Using NetRexx Built-In Math

Like Rexx, NetRexx comes with built-in support for numbers that can be manually set to very large values of precision. Compared to the two methods shown above however, the performance is extremely poor.

[edit] Note

Translation of: REXX
/* NetRexx */
 
options replace format comments java crossref savelog symbols
 
/* precision must be set manually */
 
numeric digits 190000
 
nanoFactor = 10 ** 9
 
t1 = System.nanoTime
n = 5 ** (4 ** (3 ** 2))
t2 = System.nanoTime
td = t2 - t1
say "Run time in seconds:" td / nanoFactor
say
 
check = "62060698786608744707...92256259918212890625"
sample = n.left(20)"..."n.right(20)
 
say "Expected result:" check
say " Actual result:" sample
say " digits:" n.length
say
 
if check = sample
then
say "Result confirmed"
else
say "Result does not satisfy test"
Output:
Run time in seconds: 719.660995

Expected result: 62060698786608744707...92256259918212890625
  Actual result: 62060698786608744707...92256259918212890625
         digits: 183231

Result confirmed

[edit] OCaml

open Num
open Str
open String
 
let () =
let answer = (Int 5) **/ (Int 4) **/ (Int 3) **/ (Int 2) in
let answer_string = string_of_num answer in
Printf.printf "has %d digits: %s ... %s\n"
(length answer_string)
(first_chars answer_string 20)
(last_chars answer_string 20)

A more readable program can be obtained using Delimited Overloading:

let () =
let answer = Num.(5**4**3**2) in
let s = Num.(to_string answer) in
Printf.printf "has %d digits: %s ... %s\n"
(String.length s) (Str.first_chars s 20) (Str.last_chars s 20)
Output:
has 183231 digits: 62060698786608744707 ... 92256259918212890625

[edit] ooRexx

 
--REXX program to show arbitrary precision integers.
numeric digits 200000
check = '62060698786608744707...92256259918212890625'
 
start = .datetime~new
n = 5 ** (4 ** (3**2))
time = .datetime~new - start
say 'elapsed time for the calculation:' time
say
sampl = left(n, 20)"..."right(n, 20)
 
say ' check:' check
say 'Sample:' sampl
say 'digits:' length(n)
say
 
if check=sampl then say 'passed!'
else say 'failed!'
 

[edit] Oz

declare
Pow5432 = {Pow 5 {Pow 4 {Pow 3 2}}}
S = {Int.toString Pow5432}
Len = {Length S}
in
{System.showInfo
{List.take S 20}#"..."#
{List.drop S Len-20}#" ("#Len#" Digits)"}
Output:
62060698786608744707...92256259918212890625 (183231 Digits)

[edit] PARI/GP

An alternate, but slightly slower, method for counting decimal digits is #Str(n). Note that sizedigit is not exact—in particular, it may be off by one (thus the function below).

digits(x)={
my(s=sizedigit(x)-1);
if(x<10^s,s,s+1)
};
 
N=5^(4^(3^2));
[precision(N*1.,20), Mod(N,10^20), digits(N)]
Output:
[6.20606987866087447074832055728 E183230, Mod(92256259918212890625, 100000000000000000000), 183231]

[edit] Pascal

Works with: Free_Pascal
Library: math
Library: GMP

FreePascal comes with a header unit for gmp. Starting from the C program, this is a Pascal version:

program GMP_Demo;
 
uses
math, gmp;
 
var
a: mpz_t;
out: pchar;
len: longint;
i: longint;
 
begin
mpz_init_set_ui(a, 5);
mpz_pow_ui(a, a, 4 ** (3 ** 2));
len := mpz_sizeinbase(a, 10);
writeln('GMP says size is: ', len);
out := mpz_get_str(NIL, 10, a);
writeln('Actual size is: ', length(out));
write('Digits: ');
for i := 0 to 19 do
write(out[i]);
write ('...');
for i := len - 20 to len do
write(out[i]);
writeln;
end.
Output:
GMP says size is: 183231
Actual size is:   183231
Digits: 62060698786608744707...92256259918212890625

[edit] Perl

Perl's Math::BigInt core module handles big integers:

use Math::BigInt;
my $x = Math::BigInt->new('5') ** Math::BigInt->new('4') ** Math::BigInt->new('3') ** Math::BigInt->new('2');
my $y = "$x";
printf("5**4**3**2 = %s...%s and has %i digits\n", substr($y,0,20), substr($y,-20), length($y));

You can enable "transparent" big integer support by enabling the bigint pragma:

use bigint;
my $x = 5**4**3**2;
my $y = "$x";
printf("5**4**3**2 = %s...%s and has %i digits\n", substr($y,0,20), substr($y,-20), length($y));

Math::BigInt is very slow. Perl 5.10 was about 120 times slower than Ruby 1.9.2 (on one computer); Perl used more than one minute, but Ruby used less than one second.

Output:
$ time perl transparent-bigint.pl 
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
1m4.28s real 1m4.30s user 0m0.00s system

[edit] Perl 6

given ~[**] 5, 4, 3, 2 {
say "5**4**3**2 = {.substr: 0,20}...{.substr: *-20} and has {.chars} digits";
}
Output:
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits

[edit] PHP

PHP has two separate arbitrary-precision integer services.

The first is the BC library.[2] It represents the integers as strings, so may not be very efficient. The advantage is that it is more likely to be included with PHP.

<?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y));
?>
Output:
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits

The second is the GMP library.[3] It represents the integers as an opaque type, so may be faster. However, it is less likely to be compiled into your version of PHP (it isn't compiled into mine).

[edit] PicoLisp

(let L (chop (** 5 (** 4 (** 3 2))))
(prinl (head 20 L) "..." (tail 20 L))
(length L) )
Output:
62060698786608744707...92256259918212890625
-> 183231

[edit] Pike

> string res = (string)pow(5,pow(4,pow(3,2)));
> res[..19] == "62060698786608744707";
Result: 1
> res[<19..] == "92256259918212890625";
Result: 1
> sizeof(result);
Result: 183231

[edit] PureBasic

PureBasic has in its current version (today 4.50) no internal support for large numbers, but there are several free libraries for this.

Using Decimal.pbi, e.g. the same included library as in Long multiplication#PureBasic, this task is solved as below.

IncludeFile "Decimal.pbi"
 
;- Declare the variables that will be used
Define.Decimal *a
Define n, L$, R$, out$, digits.s
 
;- 4^3^2 is withing 32 bit range, so normal procedures can be used
n=Pow(4,Pow(3,2))
 
;- 5^n is larger then 31^2, so the same library call as in the "Long multiplication" task is used
*a=PowerDecimal(IntegerToDecimal(5),IntegerToDecimal(n))
 
;- Convert the large number into a string & present the results
out$=DecimalToString(*a)
L$ = Left(out$,20)
R$ = Right(out$,20)
digits=Str(Len(out$))
out$="First 20 & last 20 chars of 5^4^3^2 are;"+#CRLF$+L$+#CRLF$+R$+#CRLF$
out$+"and the result is "+digits+" digits long."
 
MessageRequester("Arbitrary-precision integers, PureBasic",out$)

Arbitrary-precision integers, PureBasic.png

[edit] Python

Python comes with built-in support for arbitrary precision integers. The type of arbitrary precision integers is long in Python 2.x (overflowing operations on int's are automatically converted into long's), and int in Python 3.x.

>>> y = str( 5**4**3**2 )
>>> print ("5**4**3**2 = %s...%s and has %i digits" % (y[:20], y[-20:], len(y)))
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits

[edit] R

R does not come with built-in support for arbitrary precision integers, but it can be implemented with the GMP library (there is also an interface to bc).

library(gmp)
large=pow.bigz(5,pow.bigz(4,pow.bigz(3,2)))
largestr=as.character(large)
cat("first 20 digits:",substr(largestr,1,20),"\n",
"last 20 digits:",substr(largestr,nchar(largestr)-19,nchar(largestr)),"\n",
"number of digits: ",nchar(largestr),"\n")
Output:
first 20 digits: 62060698786608744707 
 last 20 digits: 92256259918212890625 
 number of digits:  183231

[edit] Racket

#lang racket
 
(define answer (number->string (foldr expt 1 '(5 4 3 2))))
(define len (string-length answer))
 
(printf "Got ~a digits~n" len)
(printf "~a ... ~a~n"
(substring answer 0 20)
(substring answer (- len 20) len))
 
Output:
Got 183231 digits

62060698786608744707 ... 92256259918212890625

[edit] REXX

REXX comes with built-in support for fixed precision integers that can be manually set to a large value of precision (digits).
Most REXXes have a practical limit of around eight million bytes, but that is mostly an underlying limitation of addressing virtual storage.

[edit] manual setting of digits

Note: both REXX versions (below) don't work with:

  •   PC/REXX
  •   Personal REXX

as those REXX versions have a maximum of around 3,700 or less for numeric digits.
The 3,700 limit is based on the setting of RXISA, program size, and the amount of storage used by REXX variables.

Both (below) REXX programs have been tested with:

  •   PC/REXX             (can't execute correctly)
  •   Personal REXX   (can't execute correctly)
  •   Regina REXX
  •   R4
  •   ROO
  •   ooRexx                 (tested by Walter Pachl)
/*REXX program to calculate and demonstrate arbitrary precision numbers.*/
numeric digits 200000
 
n = 5 ** (4 ** (3 ** 2)) /*calc. multiple exponentations. */
 
check = 62060698786608744707...92256259918212890625
sampl = left(n, 20) || '...' || right(n, 20)
 
say ' check:' check
say 'sample:' sampl
say
if check==sampl then say 'passed!'
else say 'failed!'
/*stick a fork in it, we're done.*/

output

 check: 62060698786608744707...92256259918212890625
sample: 62060698786608744707...92256259918212890625
digits: 183231

passed!

[edit] automatic setting of digits

/*REXX program to calculate and demonstrate arbitrary precision numbers.*/
numeric digits 5 + 1 /*6 is needed (not 5) for ooRexx.*/
n=5** (4** (3** 2)) /*calc. multiple exponentations. */
 
parse var n 'E' pow . /*POW might be null, so N is OK.*/
 
if pow\=='' then do /*general case: POW might be < 0*/
numeric digits abs(pow)+9 /*recalc. with more digits.*/
n=5** (4** (3** 2)) /*calc. multiple exponentations. */
end
 
check = 62060698786608744707...92256259918212890625
sampl = left(n, 20)'...'right(n, 20)
 
say ' check:' check
say 'sample:' sampl
say 'digits:' length(n)
say
if check==sampl then say 'passed!'
else say 'failed!'
/*stick a fork in it, we're done.*/

output is the same as the 1st version.

ooRexx gives me 

      5 *-* n=5** (4** (3** 2))  /*calc. multiple exponentations. */
 Error 26 running Z:\huge.rex line 5:  Invalid whole number
 Error 26.8:  Operand to the right of the power operator (**) must be a whole number; found "2.6214E+5" 
Other Rexx-es don't??

No answer yet. numeric digits 6 at the start fixes the problem for ooRexx --Walterpachl (talk) 18:47, 5 November 2013 (UTC)

Yes, Regina and R4 are both very lenient (liberal?) in their usage of exponents.
Also, the (internal) subroutines of these REXXes may use a   numeric digits 9,
thereby bypassing the use/limit of numeric digits 5   (as in the older/replaced 2nd version).

[edit] Ruby

Ruby comes with built-in support for arbitrary precision integers. The type of arbitrary precision integers is Bignum; overflowing operations on Fixnum's are automatically converted into Bignum's.

irb(main):001:0> y = ( 5**4**3**2 ).to_s; puts "5**4**3**2 = #{y[0..19]}...#{y[-20..-1]} and has #{y.length} digits"
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
Output:
$ time ruby19 -e 'y = ... digits"'
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
    0m0.52s real     0m0.47s user     0m0.05s system

[edit] Run BASIC

x$ = str$( 5^(4^(3^2))) 
print "Length:";len( x$)
print left$( x$, 20); "......"; right$( x$, 20)
Output:
Length:183231
62060698786608744707......92256259918212890625

[edit] Sather

class MAIN is
main is
r:INTI;
p1 ::= "62060698786608744707";
p2 ::= "92256259918212890625";
 
-- computing 5^(4^(3^2)), it could be written
-- also e.g. (5.inti)^((4.inti)^((3.inti)^(2.inti)))
r  := (3.pow(2)).inti;
r  := (4.inti).pow(r);
r  := (5.inti).pow(r);
 
sr ::= r.str; -- string rappr. of the number
if sr.head(p1.size) = p1
and sr.tail(p2.size) = p2 then
#OUT + "result is ok..\n";
else
#OUT + "oops\n";
end;
#OUT + "# of digits: " + sr.size + "\n";
end;
end;
Output:
result is ok..
# of digits: 183231

[edit] Scala

Scala does not come with support for arbitrary precision integers powered to arbitrary precision integers, except if performed on a module. It can use arbitrary precision integers in other ways, including powering them to 32-bits integers.

scala> BigInt(5) modPow (BigInt(4) pow (BigInt(3) pow 2).toInt, BigInt(10) pow 20)
res21: scala.math.BigInt = 92256259918212890625
 
scala> (BigInt(5) pow (BigInt(4) pow (BigInt(3) pow 2).toInt).toInt).toString
res22: String = 6206069878660874470748320557284679309194219265199117173177383244
78446890420544620839553285931321349485035253770303663683982841794590287939217907
89641300156281305613064874236198955114921296922487632406742326659692228562195387
46210423235340883954495598715281862895110697243759768434501295076608139350684049
01191160699929926568099301259938271975526587719565309995276438998093283175080241
55833224724855977970015112594128926594587205662421861723789001208275184293399910
13912158886504596553858675842231519094813553261073608575593794241686443569888058
92732524316323249492420512640962691673104618378381545202638771401061171968052873
21414945463925055899307933774904078819911387324217976311238875802878310483037255
33789567769926391314746986316354035923183981697660495275234703657750678459919...
scala> res22 take 20
res23: String = 62060698786608744707
 
scala> res22 length
res24: Int = 183231
 
scala>

[edit] Scheme

R4RS and R5RS encourage, and R6RS requires, that exact integers be of arbitrary precision.

(define x (expt 5 (expt 4 (expt 3 2))))
(define y (number->string x))
(define l (string-length y))
(display (string-append "5**4**3**2 = " (substring y 0 20) "..." (substring y (- l 20) l) " and has " (number->string l) " digits"))
(newline)
Output:
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits

[edit] Seed7

$ include "seed7_05.s7i";
include "bigint.s7i";
 
const proc: main is func
local
var bigInteger: fiveToThePowerOf262144 is 5_ ** 4 ** 3 ** 2;
var string: numberAsString is str(fiveToThePowerOf262144);
begin
writeln("5**4**3**2 = " <& numberAsString[..20] <&
"..." <& numberAsString[length(numberAsString) - 19 ..]);
writeln("decimal digits: " <& length(numberAsString));
end func;
Output:
5**4**3**2 = 62060698786608744707...92256259918212890625
decimal digits: 183231

[edit] SIMPOL

This example is incomplete. Number of digits in result not given. Please ensure that it meets all task requirements and remove this message.

SIMPOL supports arbitrary precision integers powered to arbitrary precision integers. This is the only integer data type in SIMPOL. SIMPOL supports conversion from its integer data type to other formats when calling external library functions.

constant FIRST20 "62060698786608744707"
constant LAST20 "92256259918212890625"
 
function main()
integer i
string s, s2
 
i = .ipower(5, .ipower(4, .ipower(3, 2)))
s2 = .tostr(i, 10)
if .lstr(s2, 20) == FIRST20 and .rstr(s2, 20) == LAST20
s = "Success! The integer matches both the first 20 and the last 20 digits. There are " + .tostr(.len(s2), 10) + " digits in the result.{d}{a}"
else
s = ""
if .lstr(s2, 20) != FIRST20
s = "Failure! The first 20 digits are: " + .lstr(s2, 20) + " but they should be: " + FIRST20 + "{d}{a}"
end if
if .rstr(s2, 20) != LAST20
s = s + "Failure! The first 20 digits are: " + .lstr(s2, 20) + " but they should be: " + LAST20 + "{d}{a}"
end if
end if
end function s

[edit] Smalltalk

This code in Squeak Smalltalk returns a string containing the first 20 digits, last 20 digits and length of the result.

A very simple approach:

|num|
num := (5 raisedTo: (4 raisedTo: (3 raisedTo: 2))) asString.
Transcript
show: (num first: 20), '...', (num last: 20); cr;
show: 'digits: ', num size asString.

On a Transcript window:

62060698786608744707...92256259918212890625
digits: 183231

And a more advanced one:

|num numstr|
num := (2 to: 5) fold: [:exp :base| base raisedTo: exp].
numstr := num asString.
'<1s>...<2s> digits:<3p>'
expandMacrosWith: (numstr first: 20)
with: (numstr last: 20)
with: numstr size.
Output:
'62060698786608744707...92256259918212890625  digits: 183231'

[edit] Standard ML

let
val answer = IntInf.pow (5, IntInf.toInt (IntInf.pow (4, IntInf.toInt (IntInf.pow (3, 2)))))
val s = IntInf.toString answer
val len = size s
in
print ("has " ^ Int.toString len ^ " digits: " ^
substring (s, 0, 20) ^ " ... " ^
substring (s, len-20, 20) ^ "\n")
end;

it took too long to run

[edit] Tcl

Tcl supports arbitrary precision integers (and an exponentiation operator) from 8.5 onwards.

Works with: Tcl version 8.5
set bigValue [expr {5**4**3**2}]
puts "5**4**3**2 has [string length $bigValue] digits"
if {[string match "62060698786608744707*92256259918212890625" $bigValue]} {
puts "Value starts with 62060698786608744707, ends with 92256259918212890625"
} else {
puts "Value does not match 62060698786608744707...92256259918212890625"
}
Output:
5**4**3**2 has 183231 digits
Value starts with 62060698786608744707, ends with 92256259918212890625

[edit] TXR

@(bind (f20 l20 ndig) 
@(let* ((num (expt 5 4 3 2))
(str (format nil "~s" num))
(len (length str)))
'(,(sub-str str 0 20) ,(sub-str str (- len 20) len) ,len)))
@(bind f20 "62060698786608744707")
@(bind l20 "92256259918212890625")
@(output)
@f20...@l20
ndigits=@ndig
@(end)
Output:
62060698786608744707...92256259918212890625
ndigits=183231

[edit] Ursala

There are no infix arithmetic operators in the language, but there is a power function in the bcd library, which is part of the standard distribution from the home site.

There is no distinction between ordinary and arbitrary precision integers, but the binary converted decimal representation used here is more efficient than the usual binary representation in calculations that would otherwise be dominated by the conversion to decimal output.

#import std
#import nat
#import bcd
 
#show+
 
main = <.@ixtPX take/$20; ^|T/~& '...'--@x,'length: '--@h+ %nP+ length@t>@h %vP power=> <5_,4_,3_,2_>

With this calculation taking about a day to run, correct results are attainable but not performant.

62060698786608744707...92256259918212890625
length: 183231

[edit] zkl

Using the GNU big num library:

var BN=Import("zklBigNum");
n:=BN(5).pow(BN(4).pow(BN(3).pow(2)));
s:=n.toString();
"%,d".fmt(s.len()).println();
println(s[0,20],"...",s[-20,*]);
Output:
183,231
62060698786608744707...92256259918212890625
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox