How to find the 18th steady-3 number ?

1 次查看(过去 30 天)
Syed Hafiz
Syed Hafiz 2021-4-23
评论: Jan 2021-4-23
A number n is considered to be a steady-p number if n^p ends in the same digits. For example, the number n=25 is a steady-3 number since 25^3 = 15625. The number n=251 is also a steady-3 number since 251^3 = 15813251.
Determine the 18th steady-3 number that exists starting from the number 1. The 1st steady-3 number is n=1 (1^3 = 1). The 2nd steady-2 number is n=4 (4^3 = 64). You may want to use the num2str() function.

回答(1 个)

Jan
Jan 2021-4-23
编辑:Jan 2021-4-23
Let's assume the problem can be solved in Matlab without high precision toolboxes. Numbers can be represented exactly up to 2^53. Then searching for cubic numbers works until (2^53)^(1/3), which is 208063. This number looks small enought for a dump brute force approach.
The question looks like a homework. So please post, what you have tried so far and ask a specific question.
The hint of the num2str function is misleading. It is more efficient not to convert the data types. The MOD() function is better. Remember, that the number k has n = floor(log10(k)) + 1 digits. Then mod(k.^3, 10.^n) replies the rightmost n digits.
This is half of the required code already. Please try to finish this and ask again in case of problems.
PS. The result is smaller than 1000.
  4 个评论
Syed Hafiz
Syed Hafiz 2021-4-23
Never mind i figured it out, the log10 thing didn't come intuitively to me though, so took some time to wrap my head around it, thanks once again !
Jan
Jan 2021-4-23
Omit the brute clearing header. Especially clear all removes all loaded functions from the memory. Reloading them from the slow disk wastes time only without any benefits. Teachers mention this header, because they have been told to use it when they were students. This is "cargo cult programming".
Here a version without a loop:
k = 1:208063;
n = floor(log10(k)) + 1;
result = k(mod(k.^3, 10.^n) == k);
fprintf('%3d: %8d\n', [1:numel(result); result]);
num2str is a wrapper for sprintf. Then it is faster to call it directly. Here a version with string conversion:
c = 0;
for k = 1:1000
if endsWith(sprintf('%d', k^3), sprintf('%d', k))
c = c + 1;
fprintf('%3d: %6d\n', c, k);
end
end

请先登录,再进行评论。

类别

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