find the last ten digits of 1^1 + 2^2 + ... + 1000^1000
8 views (last 30 days)
Show older comments
how to Create a function to find the last ten digits of 1^1 + 2^2 + ... + 1000^1000 using M-script
5 Comments
Walter Roberson
on 3 Jan 2013
No, that will not work. x^x can exceed 2^53 and so x^x would have lost digits before being added to y. This starts happening from 14 onwards. And after 142, x^x would be calculated as infinity because it exceeds 1E308
Accepted Answer
More Answers (2)
Jan
on 3 Jan 2013
Edited: Jan
on 3 Jan 2013
You do not have to calculate i^i explicitly to find the trailing n digits of this number. It is enough to get the trailing n digits of each partial product, which can be achieved by the mod command. The same can be applied for the sum also. Finally 8 lines of very straight Matlab code are enough, and no special toolbox functions are required.
Computing time is 0.025 seconds on my Core2Duo, Matlab2009a/64. The last digit appears 3 times.
[EDITED] As said already, you can get the last 10 digits of x^x without calculating this potentially large value explicitly:
P = 1;
for ix = 1:x
P = mod(P * x, 1e10);
end
Now P contains the last 10 digits of x^x. Ok? The sum can be created equivalently.
Limitation: This fails, when x*1e10 exceeds 2^53.
6 Comments
Walter Roberson
on 4 Jan 2013
binary decomposition of the exponent is a technique that will work fine up to
(2^52)^(2^52)
Jan
on 4 Jan 2013
@vivek: It looks like you got 4 working solutions in this thread. Is your problem solved now?
Sean de Wolski
on 2 Jan 2013
This is a good way to jog the brain for the first time in 2013!
last10 = trailingdigit(sum(vpi(1:1000).^vpi(1:1000)),10)
4 Comments
Walter Roberson
on 3 Jan 2013
Then you cannot use Sean's approach. You should, however, be able to look at the source for the two FEX contributions I pointed out, and copy and paste the source into a local file.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!