Arbitrary-precision integers (included): Difference between revisions
Arbitrary-precision integers (included) (view source)
Revision as of 05:40, 10 May 2024
, 19 days ago→{{header|langur}}
No edit summary |
Langurmonkey (talk | contribs) |
||
(34 intermediate revisions by 14 users not shown) | |||
Line 24:
{{trans|Python}}
<
print(‘5^4^3^2 = #....#. and has #. digits’.format(y[0.<20], y[(len)-20..], y.len))</
{{out}}
Line 33:
=={{header|8th}}==
<
200000 n#
5 4 3 2 bfloat ^ ^ ^
Line 39:
dup s:len . " digits" . cr
dup 20 s:lsub . "..." . 20 s:rsub . cr
</syntaxhighlight>
{{out}}
<pre>
Line 47:
=={{header|ACL2}}==
<
(include-book "arithmetic-3/floor-mod/floor-mod" :dir :system)
Line 65:
(subseq s 0 20)
(mod x (expt 10 20))
(1- (length s)))))</
{{out}}
Line 72:
=={{header|Ada}}==
{{libheader|GMP}} Using GMP, Ada bindings provided in GNATColl
<
with GNATCOLL.GMP; use GNATCOLL.GMP;
with GNATCOLL.GMP.Integers; use GNATCOLL.GMP.Integers;
Line 87:
Put_Line ("Size is:"& Natural'Image (len));
Put_Line (str (1 .. 20) & "....." & str (len - 19 .. len));
end ArbitraryInt;</
{{out}}
<pre>Size is: 183231
Line 93:
=={{header|ALGOL 68}}==
<
BEGIN
COMMENT
Line 134:
printf (($gxg(0)l$, "Number of digits:", digits))
END
</
<pre>
First 20 digits: 62060698786608744707
Line 142:
=={{header|Alore}}==
<
var len as Int
var result as Str
Line 150:
Print(result[:20])
Print(result[len-20:])
end</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">num: to :string 5^4^3^2
print [first.n: 20 num ".." last.n: 20 num "=>" size num "digits"]</syntaxhighlight>
{{out}}
<pre>62060698786608744707 .. 92256259918212890625 => 183231 digits</pre>
=={{header|bc}}==
<
y = 5 ^ 4 ^ 3 ^ 2
Line 160 ⟶ 170:
" Last 20 digits: "; y % (10 ^ 20)
"Number of digits: "; c
quit</
Output: <pre>$ time bc 5432.bc
Line 168 ⟶ 178:
0m24.81s real 0m24.81s user 0m0.00s system</pre>
=={{header|Bracmat}}==
At the prompt type the following one-liner:
<
{!} 62060698786608744707...92256259918212890625
length 183231
S 2,46 sec</
=={{header|C}}==
=== {{libheader|GMP}} ===
<
#include <stdio.h>
#include <string.h>
Line 199 ⟶ 208:
// free(s); /* we could, but we won't. we are exiting anyway */
return 0;
}</
{{out}}
<pre>GMP says size is: 183231
Line 206 ⟶ 215:
==={{libheader|OpenSSL}}===
OpenSSL is about 17 times slower than GMP (on one computer), but still fast enough for this small task.
<
#include <openssl/bn.h> /* BN_*() */
Line 270 ⟶ 279:
return 0;
}</
{{out}}
<pre>$ make LDLIBS=-lcrypto 5432
Line 285 ⟶ 294:
<code>System.Numerics.BigInteger</code> was added in C# 4. The exponent of <code>BigInteger.Pow()</code> is limited to a 32-bit signed integer, which is not a problem in this specific task.
{{works with|C sharp|C#|4+}}
<
using System.Diagnostics;
using System.Linq;
Line 307 ⟶ 316:
Console.WriteLine("n digits = {0}", result.Length);
}
}</
{{out}}
<pre>
Line 318 ⟶ 327:
=== {{libheader|Boost-Multiprecision (GMP Backend)}} ===
To compile link with GMP <code>-lgmp</code>
<
#include <boost/multiprecision/gmp.hpp>
#include <string>
Line 341 ⟶ 350:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>62060698786608744707...92256259918212890625</pre>
Line 347 ⟶ 356:
=={{header|Ceylon}}==
Be sure to import ceylon.whole in your module.ceylon file.
<
wholeNumber,
two
Line 371 ⟶ 380:
print("The last twenty digits are ``bigString[(bigSize - 20)...]``");
print("The number of digits in 5^4^3^2 is ``bigSize``");
}</
{{output}}
<pre>The first twenty digits are 62060698786608744707
Line 378 ⟶ 387:
=={{header|Clojure}}==
<
(def big (->> 2 (exp 3) (exp 4) (exp 5)))
Line 389 ⟶ 398:
(println (str (.substring sbig 0 20) ".."
(.substring sbig (- (count sbig) 20)))
(str "(" (count sbig) " digits)"))</
{{out}}
<pre>output> 62060698786608744707..92256259918212890625 (183231 digits)</pre>
Redefining ''exp'' as follows speeds up the calculation of ''big'' about a hundred times:
<
(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))))</
=={{header|CLU}}==
This program uses the <code>bigint</code> type that is supplied with Portable CLU, in
<code>misc.lib</code>. The program must be merged with that library in order to work.
The type is not included in the CLU specification, however it is included as a library
with the reference implementation.
<syntaxhighlight lang="clu">start_up = proc ()
% Get bigint versions of 5, 4, 3 and 2
five: bigint := bigint$i2bi(5)
four: bigint := bigint$i2bi(4)
three: bigint := bigint$i2bi(3)
two: bigint := bigint$i2bi(2)
% Calculate 5**4**3**2
huge_no: bigint := five ** four ** three ** two
% Turn answer into string
huge_str: string := bigint$unparse(huge_no)
% Scan for first digit (the string will have some leading whitespace)
i: int := 1
while huge_str[i] = ' ' do i := i + 1 end
po: stream := stream$primary_output()
stream$putl(po, "First 20 digits: "
|| string$substr(huge_str, i, 20))
stream$putl(po, "Last 20 digits: "
|| string$substr(huge_str, string$size(huge_str)-19, 20))
stream$putl(po, "Amount of digits: "
|| int$unparse(string$size(huge_str) - i + 1))
end start_up</syntaxhighlight>
{{out}}
<pre>First 20 digits: 62060698786608744707
Last 20 digits: 92256259918212890625
Amount of digits: 183231</pre>
=={{header|COBOL}}==
Line 406 ⟶ 453:
{{works with|GnuCOBOL}}
{{libheader|GMP}}
<
program-id. arbitrary-precision-integers.
remarks. Uses opaque libgmp internals that are built into libcob.
Line 539 ⟶ 586:
end program arbitrary-precision-integers.
</syntaxhighlight>
{{out}}
Line 554 ⟶ 601:
=={{header|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'' [http://dreamsongs.com/Files/Hopl2.pdf], 2.2.2]
<
(format t "~a...~a, length ~a" (subseq s 0 20)
(subseq s (- (length s) 20)) (length s)))</
{{out}}
<pre>
62060698786608744707...92256259918212890625, length 183231
</pre>
=={{header|Crystal}}==
<syntaxhighlight lang="Crystal">require "big"
z = (BigInt.new(5) ** 4 ** 3 ** 2).to_s
zSize = z.size
puts "5**4**3**2 = #{z[0, 20]} .. #{z[zSize-20, 20]} and has #{zSize} digits"
</syntaxhighlight>
{{out}}
<pre>5**4**3**2 = 62060698786608744707 .. 92256259918212890625 and it has 183231 digits
</pre>
=={{header|D}}==
<
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);
}</
{{out}}
<pre>5^4^3^2 = 62060698786608744707..92256259918212890625 (183231 digits)</pre>
Line 575 ⟶ 634:
=={{header|Dart}}==
Originally Dart's integral type '''int''' supported arbitrary length integers, but this is no longer the case; Dart now supports integral type '''BigInt'''.
<
int fallingPowers(int base) =>
Line 586 ⟶ 645:
print('Last twenty: ${s.substring(s.length - 20)}');
print('Number of digits: ${s.length}');
</syntaxhighlight>
{{out}}
<pre>First twenty: 62060698786608744707
Line 594 ⟶ 653:
=={{header|dc}}==
{{trans|bc}}
<
5 4 3 2 ^ ^ ^ sy [y = 5 ^ 4 ^ 3 ^ 2]sz
Line 600 ⟶ 659:
[ 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</
{{out}}
<pre>$ time dc 5432.dc
Line 610 ⟶ 669:
{{libheader| System.SysUtils}}
{{libheader| Velthuis.BigIntegers}}Thanks for Rudy Velthuis, BigIntegers Library [https://github.com/rvelthuis/DelphiBigNumbers].
<syntaxhighlight lang="delphi">
program Arbitrary_precision_integers;
Line 633 ⟶ 692:
Writeln(' (', result.Length,' digits)');
readln;
end.</
{{out}}
<pre>5^4^3^2 = 62060698786608744707...92256259918212890625 (183231 digits)</pre>
Line 639 ⟶ 698:
=={{header|E}}==
E implementations are required to support arbitrary-size integers transparently.
<
? def decimal := value.toString(10); null
? decimal(0, 20)
Line 648 ⟶ 707:
? decimal.size()
# value: 183231</
=={{header|EchoLisp}}==
<
;; to save space and time, we do'nt stringify Ω = 5^4^3^2 ,
;; but directly extract tail and head and number of decimal digits
Line 684 ⟶ 743:
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Erlang}}
<
def pow(_,0), do: 1
def pow(b,e) when e > 0, do: pow(b,e,1)
Line 704 ⟶ 763:
end
end
Arbitrary.test</
{{out}}
Line 717 ⟶ 776:
As of Emacs 27.1, bignums are supported via GMP. However, there is a configurable limit on the maximum bignum size. If the limit is exceeded, an overflow error is raised.
<
(answer (number-to-string (expt 5 (expt 4 (expt 3 2)))))
(length (length answer)))
Line 726 ⟶ 785:
(substring answer (- length 20) length))
answer)
length))</
Emacs versions older than 27.1 do not support bignums, but include Calc, a library that implements big integers. The <code>calc-eval</code> function takes an algebraic formula in a string, and returns the result in a string.
{{libheader|Calc}}
<
(length (length answer)))
(message "%s has %d digits"
Line 739 ⟶ 798:
(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.
Line 749 ⟶ 808:
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]).
Line 770 ⟶ 829:
Suffix = lists:sublist(S,L-19,20),
io:format("Length: ~b~nPrefix:~s~nSuffix:~s~n",[L,Prefix,Suffix]).
</syntaxhighlight>
{{out}}
23> arbitrary:test().
Line 782 ⟶ 841:
* bigint does not support raising to a power of a bigint
* The int type does not support the power method
<
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</
=={{header|Factor}}==
Factor has built-in bignum support. Operations on integers overflow to bignums.
<
IN: rosettacode.bignums
Line 797 ⟶ 856:
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: <code>5^4^3^2 is 62060698786608744707...92256259918212890625 and has 183231 digits</code>
Line 831 ⟶ 890:
Here is the solution:
<
big_digit_pointer *exp \ iteration counter
Line 887 ⟶ 946:
\ compute 5^(4^(3^2))
big 5 big 4 big 3 big 2 big^ big^ big^ big-show CR</
and the output:
Line 902 ⟶ 961:
Here is a solution using David M. Smith's FM library, available [http://myweb.lmu.edu/dmsmith/fmlib.html here].
<
use fmzm
implicit none
Line 913 ⟶ 972:
call im_print(a / to_im(10)**(n - 19))
call im_print(mod(a, to_im(10)**20))
end program</
<pre>
Line 923 ⟶ 982:
freebasic has it's own gmp static library.
Here, a power function operates via a string and uinteger.
<
Dim Shared As Zstring * 100000000 outtext
Line 948 ⟶ 1,007:
Print Left(ans,20) + " ... "+Right(ans,20)
Print "Number of digits ";Len(ans)
Sleep</
{{out}}
<pre>GMP version 5.1.1
Line 959 ⟶ 1,018:
Fun Fact: The drastically faster arbitrary-precision integer operations that landed in Java 8 (for much faster multiplication, exponentiation, and toString) were taken from Frink's implementation and contributed to Java. Another fun fact is that it took employees from Java 11 years to integrate the improvements.
<
as = "$a" // Coerce to string
println["Length=" + length[as] + ", " + left[as,20] + "..." + right[as,20]]</
This prints <CODE>Length=183231, 62060698786608744707...92256259918212890625</CODE>
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Arbitrary-precision_integers_%28included%29}}
'''Solution'''
In the following script, the result is converted to a string, in order to calculate its size, and its first/last digits.
[[File:Fōrmulæ - Arbitrary-precision integers (included) 01.png]]
[[File:Fōrmulæ - Arbitrary-precision integers (included) 02.png]]
=={{header|GAP}}==
<
s := String(n);;
m := Length(s);
Line 980 ⟶ 1,043:
# "62060698786608744707"
s{[m-19..m]};
# "92256259918212890625"</
=={{header|Go}}==
Using <code>math/big</code>'s
<code>[https://golang.org/pkg/math/big/#Int.Exp Int.Exp]</code>.
<
import (
Line 1,003 ⟶ 1,066:
str[len(str)-20:],
)
}</
{{out}}
<pre>
Line 1,010 ⟶ 1,073:
=={{header|Golfscript}}==
<
`.. # 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:
<pre>"62060698786608744707"
Line 1,022 ⟶ 1,085:
=={{header|Groovy}}==
Solution:
<
Test:
<
assert bigString[0..<20] == "62060698786608744707"
assert bigString[-20..-1] == "92256259918212890625"
println bigString.size()</
{{out}}
<pre>183231</pre>
Line 1,035 ⟶ 1,098:
=={{header|Haskell}}==
Haskell comes with built-in support for arbitrary precision integers. The type of arbitrary precision integers is <tt>Integer</tt>.
<
main = do
let y = show (5 ^ 4 ^ 3 ^ 2)
Line 1,041 ⟶ 1,104:
putStrLn
("5**4**3**2 = " ++
take 20 y ++ "..." ++ drop (l - 20) y ++ " and has " ++ show l ++ " digits")</
{{out}}
<pre>5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits</pre>
=={{header|Hoon}}==
<syntaxhighlight lang="hoon">
=+ big=(pow 5 (pow 4 (pow 3 2)))
=+ digits=(lent (skip <big> |=(a/* ?:(=(a '.') & |))))
[digits (div big (pow 10 (sub digits 20))) (mod big (pow 10 20))]
</syntaxhighlight>
{{out}}<pre>[183.231 62.060.698.786.608.744.707 92.256.259.918.212.890.625]</pre>
Line 1,059 ⟶ 1,122:
Note: It takes far longer to convert the result to a string than it does to do the computation itself.
<
x := 5^4^3^2
write("done with computation")
Line 1,066 ⟶ 1,129:
write("The first twenty digits are ",x[1+:20])
write("The last twenty digits are ",x[0-:20])
end</
{{out|Sample run}}
<pre>->ap
Line 1,077 ⟶ 1,140:
=={{header|J}}==
J has built-in support for extended precision integers. See also [[J:Essays/Extended%20Precision%20Functions]].
<
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</
=={{header|Java}}==
Java library's <tt>BigInteger</tt> class provides support for arbitrary precision integers.
<
class IntegerPower {
Line 1,096 ⟶ 1,159:
str.substring(0, 20), str.substring(len - 20), len);
}
}</
{{out}}
<pre>5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits</pre>
Line 1,104 ⟶ 1,167:
BigInt is already implemented by Chrome and Firefox, but not yet by Explorer or Safari.
<
>>> console.log(`5**4**3**2 = ${y.slice(0,20)}...${y.slice(-20)} and has ${y.length} digits`);
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits</
=={{header|jq}}==
Line 1,112 ⟶ 1,175:
There is a BigInt.jq library for jq, but gojq, the Go implementation of jq, supports unbounded-precision integer arithmetic, so the output shown below is that produced by gojq.
<syntaxhighlight lang="jq">
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);
5|power(4|power(3|power(2))) | tostring
| .[:20], .[-20:], length
</syntaxhighlight>
{{out}}
<pre>
Line 1,128 ⟶ 1,191:
Julia includes built-in support for arbitrary-precision arithmetic using the [http://gmplib.org/ GMP] (integer) and [http://www.mpfr.org/ GNU MPFR] (floating-point) libraries, wrapped by the built-in <code>BigInt</code> and <code>BigFloat</code> types, respectively.
<
0.017507363
Line 1,137 ⟶ 1,200:
"62060698786608744707"
julia> bigstr[end-
"92256259918212890625"</syntaxhighlight>
=={{header|Klong}}==
Line 1,148 ⟶ 1,211:
=={{header|Kotlin}}==
{{trans|Java}}
<
fun main(args: Array<String>) {
Line 1,155 ⟶ 1,218:
val len = y.length
println("5^4^3^2 = ${y.substring(0, 20)}...${y.substring(len - 20)} and has $len digits")
}</
{{out}}
<pre>
5^4^3^2 = 62060698786608744707...92256259918212890625 and has 183231 digits
</pre>
=={{header|Lambdatalk}}==
Just using Javascript's BigInt
<syntaxhighlight lang="Scheme">
{def N {BI.** 5 {BI.** 4 {BI.** 3 2}}}} -> N
length: {def L {W.length {N}}} -> L = 183231
20 first digits: {W.slice 0 20 {N}} -> 62060698786608744707
20 last digits: {W.slice -20 {L} {N}} -> 92256259918212890625
</syntaxhighlight>
=={{header|langur}}==
Arbitrary precision is native in langur.
<syntaxhighlight lang="langur">val .xs = string 5 ^ 4 ^ 3 ^ 2
writeln len(.xs), " digits"
if len(.xs) > 39 and s2s(.xs, 1..20) == "62060698786608744707" and
s2s(.xs, -20 .. -1) == "92256259918212890625" {
writeln "SUCCESS"
}
</syntaxhighlight>
{{out}}
<pre>183231 digits
SUCCESS
</pre>
=={{header|Lasso}}==
Interestingly, we have to define our own method for integer powers.
<
#factor <= 0
? return 0
Line 1,178 ⟶ 1,270:
#bigint->sub(1,20) + ` ... ` + #bigint->sub(#bigint->size - 19)
"\n"
`Number of digits: ` + #bigint->size</
{{out}}
Line 1,190 ⟶ 1,282:
Note the brackets are needed to enforce the desired order of exponentiating.
<
print len( a$)
print left$( a$, 20); "......"; right$( a$, 20)</
{{out}}
183231
Line 1,199 ⟶ 1,291:
=={{header|Lua}}==
Pure/native off-the-shelf Lua does not include support for arbitrary-precision arithmetic. However, there are a number of optional libraries that do, including several from an author of the language itself - one of which this example will use. (citing the "..''may'' be used instead" allowance)
<
-- since 5$=5^4$, and IEEE754 can handle 4$, this would be sufficient:
-- n = bc.pow(bc.new(5), bc.new(4^3^2))
Line 1,205 ⟶ 1,297:
n = bc.pow(bc.new(5), bc.pow(bc.new(4), bc.pow(bc.new(3), bc.new(2))))
s = n:tostring()
print(string.format("%s...%s (%d digits)", s:sub(1,20), s:sub(-20,-1), #s))</
{{out}}
<pre>62060698786608744707...92256259918212890625 (183231 digits)</pre>
Line 1,211 ⟶ 1,303:
=={{header|Maple}}==
Maple supports large integer arithmetic natively.
<syntaxhighlight lang="maple">
> n := 5^(4^(3^2)):
> length( n ); # number of digits
Line 1,219 ⟶ 1,311:
> s[ 1 .. 20 ], s[ -20 .. -1 ]; # extract first and last twenty digits
"62060698786608744707", "92256259918212890625"
</syntaxhighlight>
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.
<syntaxhighlight lang="maple">
> interface( elisiondigitsbefore = 20, elisiondigitsafter = 20 ):
> 5^(4^(3^2)):
62060698786608744707[...183191 digits...]92256259918212890625
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica can handle arbitrary precision integers on almost any size without further declarations.
To view only the first and last twenty digits:
<
Print[StringTake[s,20]<>"..."<>StringTake[s,-20]<>" ("<>ToString@StringLength@s<>" digits)"];</
{{out}}
62060698786608744707...92256259918212890625 (183231 digits)
Line 1,237 ⟶ 1,329:
=={{header|MATLAB}}==
Using the [http://www.mathworks.com/matlabcentral/fileexchange/22725-variable-precision-integer-arithmetic Variable Precision Integer] library this task is accomplished thusly:
<
>> numDigits = order(answer) + 1
Line 1,249 ⟶ 1,341:
ans =
62060698786608744707...92256259918212890625</
=={{header|Maxima}}==
<
/* 62060698786608744707...92256259918212890625
183231 */</
=={{header|Nanoquery}}==
Integer values are arbitrary-precision by default in Nanoquery.
<
first20 = value.substring(0,20)
Line 1,270 ⟶ 1,362:
end
println "The result is " + len(str(value)) + " digits long"</
{{out}}
<pre>The first twenty digits are 62060698786608744707
Line 1,281 ⟶ 1,373:
=={{header|Nemerle}}==
{{trans|C#}}
<
using System.Numerics;
using System.Numerics.BigInteger;
Line 1,301 ⟶ 1,393:
WriteLine($"Length of result: $len digits");
}
}</
Output:
<pre>Result: 62060698786608744707 ... 92256259918212890625
Line 1,308 ⟶ 1,400:
=
=={{header|NewLisp}}==
<syntaxhighlight lang="newlisp">
;;; No built-in big integer exponentiation
(define (exp-big x n)
Line 1,329 ⟶ 1,421:
(println "First 20 digits: " (0 20 res))
(println "Last 20 digits: " (-20 20 res))))
</syntaxhighlight>
{{out}}
<pre>
Line 1,339 ⟶ 1,431:
=={{header|NetRexx}}==
=== Using Java's BigInteger Class ===
<
options replace format comments java crossref savelog symbols
Line 1,372 ⟶ 1,464:
say "Result does not satisfy test"
return</
{{out}}
<pre>
Line 1,384 ⟶ 1,476:
</pre>
=== Using Java's BigDecimal Class ===
<
options replace format comments java crossref savelog symbols
Line 1,417 ⟶ 1,509:
say "Result does not satisfy test"
return</
{{out}}
<pre>
Line 1,433 ⟶ 1,525:
==== Note ====
{{trans|REXX}}
<
options replace format comments java crossref savelog symbols
Line 1,462 ⟶ 1,554:
say "Result confirmed"
else
say "Result does not satisfy test"</
{{out}}
<pre>
Line 1,477 ⟶ 1,569:
{{libheader|bigints}}
<
var x = 5.pow 4.pow 3.pow 2
Line 1,484 ⟶ 1,576:
echo s[0..19]
echo s[s.high - 19 .. s.high]
echo s.len</
Output:
<pre>
Line 1,492 ⟶ 1,584:
=={{header|OCaml}}==
<
open Str
open String
Line 1,502 ⟶ 1,594:
(length answer_string)
(first_chars answer_string 20)
(last_chars answer_string 20)</
A more readable program can be obtained using [http://forge.ocamlcore.org/projects/pa-do/ Delimited Overloading]:
<
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)</
{{out}}
<pre>
Line 1,519 ⟶ 1,611:
Oforth handles arbitrary precision integers :
<
5 4 3 2 pow pow pow >string dup left( 20 ) . dup right( 20 ) . size . </
{{out}}
Line 1,529 ⟶ 1,621:
=={{header|Ol}}==
<
(define x (expt 5 (expt 4 (expt 3 2))))
(print
Line 1,536 ⟶ 1,628:
(mod x (expt 10 20)))
(print "totally digits: " (log 10 x))
</syntaxhighlight>
{{out}}
<pre>
Line 1,546 ⟶ 1,638:
{{trans|REXX}}
<syntaxhighlight lang="oorexx">
--REXX program to show arbitrary precision integers.
numeric digits 200000
Line 1,565 ⟶ 1,657:
if check=sampl then say 'passed!'
else say 'failed!'
</syntaxhighlight>
{{out}}
Line 1,579 ⟶ 1,671:
=={{header|Oz}}==
<
Pow5432 = {Pow 5 {Pow 4 {Pow 3 2}}}
S = {Int.toString Pow5432}
Line 1,586 ⟶ 1,678:
{System.showInfo
{List.take S 20}#"..."#
{List.drop S Len-20}#" ("#Len#" Digits)"}</
{{out}}
<pre>
Line 1,594 ⟶ 1,686:
=={{header|PARI/GP}}==
PARI/GP natively supports integers of arbitrary size, so one could just use <code>N=5^4^3^2</code>. But this would be foolish (using a lot of unneeded memory) if the task is to get just the number of, and the first and last twenty digits. The number of and the leading digits are given as 1 + the integer part, resp. 10^(fractional part + offset), of the logarithm to base 10 (not as log(N) with N=A^B, but as B*log(A); one needs at least 20 correct decimals of the log, on 64 bit machines the default precision is 39 digits, but on 32 bit architecture one should set <code>default(realprecision,30)</code> to be on the safe side). To get the trailing digits, one would use modular exponentiation which is also built-in and very efficient even for extremely huge exponents:
<
[L\1+1, 10^frac(L)\10^(1-n), lift(m)] \\ where x\y = floor(x/y) but more efficient
}
print("Length, first and last 20 digits of 5^4^3^2: ", num_first_last_digits()) \\ uses default values a=5, b=4^3^2, n=20</
{{out}}
<pre>Length, first and last 20 digits of 5^4^3^2: [183231, 62060698786608744707, 92256259918212890625]</pre>
Line 1,603 ⟶ 1,695:
An alternate but much slower method for counting decimal digits is <code>#Str(n)</code>. Note that <code>sizedigit</code> is not exact—in particular, it may be off by one (thus the function below).
<
my(s=sizedigit(x)-1);
if(x<10^s,s,s+1)
Line 1,609 ⟶ 1,701:
N=5^(4^(3^2));
[precision(N*1.,20), Mod(N,10^20), digits(N)]</
{{out}}
<pre>[6.20606987866087447074832055728 E183230, Mod(92256259918212890625, 100000000000000000000), 183231]</pre>
Line 1,618 ⟶ 1,710:
{{libheader|GMP}}
FreePascal comes with a header unit for gmp. Starting from the C program, this is a Pascal version:
<
uses
Line 1,643 ⟶ 1,735:
write(out[i]);
writeln;
end.</
{{out}}
<pre>
Line 1,653 ⟶ 1,745:
=={{header|Perl}}==
Perl's <tt>Math::BigInt</tt> core module handles big integers:
<
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 <tt>bigint</tt> pragma:
<
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));</
<tt>Math::BigInt</tt> 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.
{{out}}
<
5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
1m4.28s real 1m4.30s user 0m0.00s system</
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/mpfr}}
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
Line 1,681 ⟶ 1,773:
<span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"5^4^3^2 = %s (%s)\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 1,691 ⟶ 1,783:
The first is the BC library.[http://us3.php.net/manual/en/book.bc.php] 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.
<
$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));
?></
{{out}}
<pre>
Line 1,700 ⟶ 1,792:
</pre>
The second is the GMP library.[http://us3.php.net/manual/en/book.gmp.php] 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).
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
X = to_string(5**4**3**2),
Y = len(X),
println("Result: "),
print("Number of digits: "), println(Y),
println("First 20 digits: " ++ X[1..20]),
println("Last 20 digits: " ++ X[Y-19..Y]).</syntaxhighlight>
=={{header|PicoLisp}}==
<
(prinl (head 20 L) "..." (tail 20 L))
(length L) )</
{{out}}
<pre>62060698786608744707...92256259918212890625
Line 1,710 ⟶ 1,812:
=={{header|Pike}}==
<
> res[..19] == "62060698786608744707";
Result: 1
Line 1,716 ⟶ 1,818:
Result: 1
> sizeof(result);
Result: 183231</
=={{header|PowerShell}}==
<
$BigNumber = [BigInt]::Pow( 5, [BigInt]::Pow( 4, [BigInt]::Pow( 3, 2 ) ) )
Line 1,727 ⟶ 1,829:
# Display number of digits
$BigNumberString.Length</
{{out}}
<pre>62060698786608744707...92256259918212890625
183231</pre>
=={{header|Processing}}==
<syntaxhighlight lang="java">import java.math.BigInteger;
// Variable definitions
BigInteger _5, _4, powResult;
_5 = BigInteger.valueOf(5);
_4 = BigInteger.valueOf(4);
//calculations
powResult = _5.pow(_4.pow(9).intValueExact());
String powStr = powResult.toString();
int powLen = powStr.length();
String powStrStart = powStr.substring(0, 20);
String powStrEnd = powStr.substring(powLen - 20);
//output
System.out.printf("5**4**3**2 = %s...%s and has %d digits%n", powStrStart, powStrEnd, powLen);
</syntaxhighlight>
{{out}}
<pre>5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits
</pre>
=={{header|Prolog}}==
Line 1,736 ⟶ 1,861:
{{works with|SWI-Prolog|6.6}}
<
task(Length) :-
N is 5^4^3^2,
Line 1,745 ⟶ 1,870:
length(Codes, Length).
</syntaxhighlight>
Query like so:
<
?- task(N).
N = 183231 ;
false.
</syntaxhighlight>
=={{header|PureBasic}}==
Line 1,759 ⟶ 1,884:
Using [http://www.purebasic.fr/english/viewtopic.php?p=309763#p309763 Decimal.pbi], e.g. the same included library as in [[Long multiplication#PureBasic]], this task is solved as below.
<
;- Declare the variables that will be used
Line 1,779 ⟶ 1,904:
out$+"and the result is "+digits+" digits long."
MessageRequester("Arbitrary-precision integers, PureBasic",out$)</
[[Image:Arbitrary-precision_integers,_PureBasic.png]]
=={{header|Python}}==
Python comes with built-in support for arbitrary precision integers. The type of arbitrary precision integers is <tt>[http://docs.python.org/library/stdtypes.html#typesnumeric long]</tt> in Python 2.x (overflowing operations on <tt>int</tt>'s are automatically converted into <tt>long</tt>'s), and <tt>[http://docs.python.org/3.1/library/stdtypes.html#typesnumeric int]</tt> in Python 3.x.
<
>>> 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</
=={{header|Quackery}}==
Line 1,812 ⟶ 1,937:
=={{header|R}}==
R does not come with built-in support for arbitrary precision integers, but it can be implemented with the GMP library
<
large
largestr
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")</
{{out}}
<pre>first 20 digits: 62060698786608744707
Line 1,825 ⟶ 1,950:
=={{header|Racket}}==
<
(define answer (number->string (foldr expt 1 '(5 4 3 2))))
Line 1,834 ⟶ 1,959:
(substring answer 0 20)
(substring answer (- len 20) len))
</syntaxhighlight>
{{out}}<pre>Got 183231 digits
62060698786608744707 ... 92256259918212890625</pre>
Line 1,840 ⟶ 1,965:
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|
<syntaxhighlight lang="raku" line>
given [**] 5, 4, 3, 2 {
use Test;
ok /^ 62060698786608744707 <digit>* 92256259918212890625 $/,
'5**4**3**2 has expected first and last twenty digits';
printf 'This number has %d digits', .chars;
}</syntaxhighlight>
{{out}}
<pre>ok 1 - 5**4**3**2
This number has 183231 digits</pre>
=={{header|REXX}}==
Line 1,867 ⟶ 1,997:
:::* ROO
:::* ooRexx (tested by Walter Pachl)
<
numeric digits 200000 /*two hundred thousand decimal digits. */
Line 1,881 ⟶ 2,011:
if true == rexx then say 'passed!' /*either it passed, ··· */
else say 'failed!' /* or it didn't. */
/*stick a fork in it, we're all done. */</
{{output|output}}
<pre>
Line 1,892 ⟶ 2,022:
===automatic setting of decimal digits===
<
numeric digits 5 /*just use enough digits for 1st time. */
Line 1,913 ⟶ 2,043:
if true == rexx then say 'passed!' /*either it passed, ··· */
else say 'failed!' /* or it didn't. */
/*stick a fork in it, we're all done. */</
{{out|output|text= is the same as the 1<sup>st</sup> REXX version.}}
<br><br>
Line 1,920 ⟶ 2,050:
Ruby comes with built-in support for arbitrary precision integers.
<
puts "5**4**3**2 = #{y[0..19]}...#{y[-20..-1]} and has #{y.length} digits"
</syntaxhighlight>
{{out}}
<pre>
Line 1,929 ⟶ 2,059:
=={{header|Run BASIC}}==
<
print "Length:";len( x$)
print left$( x$, 20); "......"; right$( x$, 20)</
{{out}}
<pre>Length:183231
Line 1,939 ⟶ 2,069:
This is accomplished via the `num` crate. This used to be part of the standard library, but was relegated to an external crate when Rust hit 1.0. It is still owned and maintained by members of the Rust core team and is the de-facto library for numerical generics and arbitrary precision arithmetic.
<
use num::bigint::BigUint;
use num::FromPrimitive;
Line 1,954 ⟶ 2,084:
println!("Number of digits: {}", answer_as_string.len());
println!("First and last digits: {:?}..{:?}", first_twenty, last_twenty);
}</
{{out}}
<pre>
Line 1,962 ⟶ 2,092:
=={{header|Sather}}==
<
main is
r:INTI;
Line 1,983 ⟶ 2,113:
#OUT + "# of digits: " + sr.size + "\n";
end;
end;</
{{out}}
<pre>result is ok..
Line 1,990 ⟶ 2,120:
=={{header|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.
<
res21: scala.math.BigInt = 92256259918212890625
Line 2,010 ⟶ 2,140:
res24: Int = 183231
scala> </
=={{header|Scheme}}==
[http://people.csail.mit.edu/jaffer/r4rs_8.html#SEC52 R<sup>4</sup>RS] and [http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2.3 R<sup>5</sup>RS] encourage, and [http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-6.html#node_sec_3.4 R<sup>6</sup>RS] requires, that exact integers be of arbitrary precision.
<
(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)</
{{out}}
<pre>5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits</pre>
=={{header|Seed7}}==
<
include "bigint.s7i";
Line 2,034 ⟶ 2,164:
"..." <& numberAsString[length(numberAsString) - 19 ..]);
writeln("decimal digits: " <& length(numberAsString));
end func;</
{{out}}
<pre>
Line 2,042 ⟶ 2,172:
=={{header|Sidef}}==
<
var y = x.to_s
printf("5**4**3**2 =
{{out}}
<pre>
Line 2,053 ⟶ 2,183:
{{incomplete|SIMPOL|Number of digits in result not given.}}
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 LAST20 "92256259918212890625"
Line 2,073 ⟶ 2,203:
end if
end if
end function s</
=={{header|Smalltalk}}==
Line 2,079 ⟶ 2,209:
A very simple approach:
<
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:
Line 2,089 ⟶ 2,219:
digits: 183231</pre>
And a more advanced one:
<
num := (2 to: 5) fold: [:exp :base| base raisedTo: exp].
numstr := num asString.
Line 2,095 ⟶ 2,225:
expandMacrosWith: (numstr first: 20)
with: (numstr last: 20)
with: numstr size.</
{{out}}
<pre>'62060698786608744707...92256259918212890625 digits: 183231'</pre>
Line 2,102 ⟶ 2,232:
=={{header|SPL}}==
<
n = #.size(t)
#.output(n," digits")
#.output(#.mid(t,1,20),"...",#.mid(t,n-19,20))</
{{out}}
<pre>
Line 2,113 ⟶ 2,243:
=={{header|Standard ML}}==
<
val answer = IntInf.pow (5, IntInf.toInt (IntInf.pow (4, IntInf.toInt (IntInf.pow (3, 2)))))
val s = IntInf.toString answer
Line 2,121 ⟶ 2,251:
substring (s, 0, 20) ^ " ... " ^
substring (s, len-20, 20) ^ "\n")
end;</
it took too long to run
=== mLite ===
mLite does not have a logarithm function so one was constructed (see fun log10)
<
fun
ntol (0, x) = if len x < 1 then [0] else x
Line 2,175 ⟶ 2,305:
val top20 = fiveFourThreeTwo div (10^(digitCount - 20));
print "Top 20 = "; println top20;
</syntaxhighlight>
Output
<pre>
Line 2,191 ⟶ 2,321:
Tcl supports arbitrary precision integers (and an exponentiation operator) from 8.5 onwards.
{{works with|Tcl|8.5}}
<
puts "5**4**3**2 has [string length $bigValue] digits"
if {[string match "62060698786608744707*92256259918212890625" $bigValue]} {
Line 2,197 ⟶ 2,327:
} else {
puts "Value does not match 62060698786608744707...92256259918212890625"
}</
{{out}}
<pre>
5**4**3**2 has 183231 digits
Value starts with 62060698786608744707, ends with 92256259918212890625
</pre>
=={{header|Transd}}==
<syntaxhighlight lang="Scheme">#lang transd
MainModule: {
_start:(λ locals: a BigLong(5) ss StringStream() s ""
(textout to: ss (pow a (pow 4 (pow 3 2))))
(= s (str ss))
(with len (size s)
(lout "The number of digits is: " len)
(lout (sub s 0 20) " ... " (sub s (- len 20))))
)
}</syntaxhighlight>
{{out}}
<pre>
The number of digits is: 183231
62060698786608744707 ... 92256259918212890625
</pre>
=={{header|TXR}}==
<
@(let* ((str (tostring (expt 5 4 3 2)))
(len (length str)))
Line 2,214 ⟶ 2,362:
@f20...@l20
ndigits=@ndig
@(end)</
{{out}}
<pre>62060698786608744707...92256259918212890625
Line 2,223 ⟶ 2,371:
===Usage===
<
decl unbounded_int x
x.set ((x.valueof 5).pow ((x.valueof 4).pow ((x.valueof 3).pow 2)))
Line 2,248 ⟶ 2,396:
else
out "FAIL" endl console
end if</
===Output===
Line 2,260 ⟶ 2,408:
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 nat
#import bcd
Line 2,266 ⟶ 2,414:
#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.
<pre>62060698786608744707...92256259918212890625
Line 2,275 ⟶ 2,423:
{{libheader|System.Numerics}}
Addressing the issue of the '''BigInteger.Pow()''' function having the exponent value limited to '''Int32.MaxValue''' (2147483647), here are a couple of alternative implementations using a '''BigInteger''' for the exponent.
<
Imports BI = System.Numerics.BigInteger
Line 2,317 ⟶ 2,465:
End Sub
End Module</
{{out}}
<pre>n = 5^4^3^2
Line 2,334 ⟶ 2,482:
Iterative elasped: 2412.5477 milliseconds.</pre>'''Remarks:''' Not much difference in execution times for three methods. But the exponents are relatively small. If one does need to evaluate an exponent greater than '''Int32.MaxValue''', the execution time will be measured in hours.
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import math.big
import math
Line 2,346 ⟶ 2,494:
str := y.str()
println("5^(4^(3^2)) has $str.len digits: ${str[..20]} ... ${str[str.len-20..]}")
}</
{{out}}
Line 2,356 ⟶ 2,504:
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<
import "./big" for BigInt
var p = BigInt.three.pow(BigInt.two)
Line 2,365 ⟶ 2,513:
Fmt.print("5 ^ 4 ^ 3 ^ 2 has $,d digits.\n", s.count)
System.print("The first twenty are : %(s[0..19])")
System.print("and the last twenty are : %(s[-20..-1])")</
{{out}}
Line 2,376 ⟶ 2,524:
=={{header|Zig}}==
<
const bigint = std.math.big.int.Managed;
pub fn main() !void {
var
try a.pow(&a, try std.math.powi(u32, 4, try std.math.powi(u32, 3, 2)));
defer a.deinit();
var as = try a.toString(
defer
std.debug.print("{s}...{s}\n", .{ as[0..20], as[as.len - 20 ..] });
std.debug.print("{} digits\n", .{as.len});
}</
{{out}}
<pre>
Line 2,402 ⟶ 2,546:
=={{header|zkl}}==
Using the GNU big num library:
<
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,*]);</
{{out}}
<pre>
Line 2,413 ⟶ 2,557:
</pre>
{{omit from|AutoHotkey}}
{{omit from|AWK|Only has double-precision floating-point numbers.}}
{{omit from|Batch File}}
{{omit from|BBC BASIC}}
{{omit from|Brainf***}}
{{omit from|PostScript}}
|