find the last ten digits of 1^1 + 2^2 + ... + 1000^1000
Afficher commentaires plus anciens
how to Create a function to find the last ten digits of 1^1 + 2^2 + ... + 1000^1000 using M-script
5 commentaires
José-Luis
le 2 Jan 2013
What have you tried so far?
Roger Stafford
le 2 Jan 2013
If you use the proper method you can compute it numerically. The sixth digit from the right end of the answer is an '8'. That leaves you nine others to discover.
Walter Roberson
le 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
Réponse acceptée
Plus de réponses (2)
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 commentaires
Walter Roberson
le 3 Jan 2013
FEX 7908 that I linked to does a binary decomposition to minimize the number of multiplications.
Jan
le 4 Jan 2013
@Walter: I personally like the linked function. I assume that vivek cannot submit a solution of this homework question (at least I'm convinced that this is a homework) based on this function.
8 lines of straight basic Matlab code and 0.025 seconds processing time are a good argument to "keep it simple stupid".
Vivek
le 4 Jan 2013
Vivek
le 4 Jan 2013
Walter Roberson
le 4 Jan 2013
binary decomposition of the exponent is a technique that will work fine up to
(2^52)^(2^52)
Jan
le 4 Jan 2013
@vivek: It looks like you got 4 working solutions in this thread. Is your problem solved now?
Sean de Wolski
le 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 commentaires
Vivek
le 3 Jan 2013
Walter Roberson
le 3 Jan 2013
Did you download and install the vpi functions from the File Exchange (FEX) submission that Sean linked to?
Vivek
le 3 Jan 2013
Walter Roberson
le 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.
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!