필터 지우기
필터 지우기

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