Azzera filtri
Azzera filtri

Can someone provide me a simplest solution for this?

2 visualizzazioni (ultimi 30 giorni)
  2 Commenti
Koo Ian Keen
Koo Ian Keen il 25 Apr 2019
close all; clear all; clc;
%Takes about 20 seconds to run this code
iter = 0;
for n = 1:50000 %Change the 50000 to whatever values ur question wants
nstr = num2str(n);
nlength = length(nstr);
N = n^3;
Nstr = num2str(N);
Nlength = length(Nstr);
x = 0;
for i = 1:nlength
x = x + str2num(Nstr(Nlength - (i - 1)))*(10^(i - 1));
if x == n
iter = iter + 1;
else
continue
end
end
end
fprintf('The answer is %d', iter)
so this is the solution i got from my course mate, i dont understand the ' x = x + str2num(Nstr(Nlength - (i - 1)))*(10^(i - 1));' part

Accedi per commentare.

Risposte (1)

John D'Errico
John D'Errico il 25 Apr 2019
Modificato: John D'Errico il 25 Apr 2019
Easy peasy? Pretty fast too.
tic
n = 1:50000;
M = 10.^(floor(log10(n))+1);
nsteady3 = sum(n == mod(n.^3,M));
toc
Elapsed time is 0.010093 seconds.
nsteady3
nsteady3 =
40
So it looks like 40 of them that do not exceed 50000. Of course, 1 is a steady-p number for all values of p. The same applies to 5, and 25.
If n was a bit larger, things get nasty, since 50000^3 is getting close to 2^53, thus the limits of double precision arithmetic to represent integers exactly. And of course, if p were large, that would restrict things too. I'll leave it to you to figure out how to solve this for a significantly larger problem, perhaps to count the number of solutions for p=99, and n<=1e15. (Actually, this is quite easy as long as the limit on n is not too large. So n<=5e7 is quite easy even for p that large, and it should be blazingly fast.)
I got 78 such steady-99 numbers that do not exceed 5e7. It took slightly longer, but not too bad.
Elapsed time is 5.547148 seconds.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by