필터 지우기
필터 지우기

Can someone provide me a simplest solution for this?

조회 수: 2 (최근 30일)
Koo Ian Keen
Koo Ian Keen 2019년 4월 25일
편집: John D'Errico 2019년 4월 25일
  댓글 수: 2
Star Strider
Star Strider 2019년 4월 25일
Post your solution to it first.
Koo Ian Keen
Koo Ian Keen 2019년 4월 25일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

John D'Errico
John D'Errico 2019년 4월 25일
편집: John D'Errico 2019년 4월 25일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by