How to compute 3^301 as an integer

1 view (last 30 days)
As an integer and as an floating point number

Accepted Answer

John D'Errico
John D'Errico on 23 Sep 2018
You can never represent 3^301 as an integer in double precision, because it exceeds 2^53-1. It also clearly exceeds the capacity of UINT64.
This is true for any integer type in MATLAB, except for syms (the symbolic toolbox) or my own VPI toolbox, found on the file exchange.
X = sym(3)^301
X =
410674437175765127973978082146264947899391086876012309414440570235106991532497229781400618467066824164751453321793982128440538198297087323698003
X = vpi(3)^301
X =
41067443717576512797397808214626494789939108687601230941444057023510
699153249722978140061846706682416475145332179398212844053819829708732369
8003
What matters is you need to use a tool that can store the full number. Doubles, or uint64 are unable to do so.
If you only want to store it as a floating point number though, a double has no problem with doing so, as long as the result iswithin the dynamic range of a double. It is easily so.
3^301
ans =
4.10674437175765e+143
although if you pushed things too far,
3^1001
ans =
Inf
it will overflow a double. So you just need to understand the limits of a double.
If you truly intend to work woth very large numbers in floating point, then your options reduce to syms again, or to my HPF toolbox, also found on the file exchange.
So, here 40 dibits, using the symbolic tools:
X = sym(3)^301;
vpa(X,40)
ans =
4.106744371757651279739780821462649478994e143
Or in HPF, using 500 digits of precision as a floating point number:
X = hpf(3,500)^1001
X =
3966212458442419910671365779256433097896266098256444502994761104680485792040114698622334941551824185891729333090617747067852863746301856735596028175773861022082860675594962411634044322686894523823171200352765854123386843446869283314184698519162260023471518534376441033216641163191116687452396104764748408662490805691335746870685249194923663690755669212254696812828119726515539079816086550295056821764327181278269014316592308443051156946241497496031843098396519308306708565660003

More Answers (1)

Walter Roberson
Walter Roberson on 23 Sep 2018
as_int = sym(3)^301
as_fp = double(as_int)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!