Skip to content

Instantly share code, notes, and snippets.

@mast4461
Last active August 29, 2015 14:14
Show Gist options
  • Save mast4461/103a374037e8745709ab to your computer and use it in GitHub Desktop.
Save mast4461/103a374037e8745709ab to your computer and use it in GitHub Desktop.
Matlab code for computing large exponentials of the form n^m (n and m integers). Uses chars to store digits, for performance. Handles huge numbers, e.g. 2^1000. Returns the result as a string.
function str = strnpowm(base,exponent)
% Computes base^exponent (both integers) and returns the result as a string
% Handles huge numbers, e.g. 2^1000
str = char(1);
for i = 1:exponent
l = length(str);
product = repmat('0',1,l);
carry = 0;
for j = l:-1:1
% Multiply digit by base and add carry
temp = str(j)*base + carry;
% Compute carry
carry = floor(t/10);
% Store least significant digit of temp
product(j) = temp - carry*10;
end
% Prepend carry if there is a nonzero carry.
if carry > 0
str = [carry, product];
else
str = product;
end
end
% Convert to human readable integer characters
str = char(str+48);
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment