숫자의 지속성 (Persistence of Numbers)

written by jjycjn   2015. 12. 16. 02:09

숫자의 지속성(persistence)이란1 주어진 자연수 $n$에 대하여, 이 수의 각 자릿수들을 곱하는 연산을 반복하여 한자리로 변화될 때 까지 반복한 연산의 횟수로 정의한다. 좀 더 자세한 정의 및 내용은 아래의 두 글에서 확인할 수 있다.


오랜만에 (거의 1년만에) Matlab을 열어서 이 문제의 정답을 코딩해 보았다. 코딩을 하면서 가장 어려웠던 (하지만 가장 중요했던) 부분이 주어진 수 $n$의 각 자릿수를 곱하는 부분이였는데, 이를 실행하기 위해서 우선 자연수 $n$의 값을 string으로 치환한 후에 다시 이를 ($n$의 자릿수)$\times 1$의 array로 변환하는 방법을 사용하였다. 사용한 코드는 아래와 같다.2

arrayn = sscanf( sprintf( '%u', n ), '%1d' );


위 방법을 이용하면, 나머지 코딩은 간단하게 해결된다. 전체 코드는 아래와 같다.

% Persistence of Numbers (12.15.2015)

max = 1000; % maximum testing number
persistence = 5; % maximum persistence of a number

for n = 10 : max
    step = 0; % number of steps
    arrayn = sscanf( sprintf( '%u', n ), '%1d' ); 
    store = n;
    while length(arrayn) > 1
        step = step + 1;
        nextn = prod(arrayn);
        arrayn = sscanf( sprintf( '%u', nextn ), '%1d' );
        store(step) = nextn;
    end
    % uncomment below if the whole result is needed
    %{ 
    fprintf('Terminated in %d step(s): %d', step, n);
    fprintf(' -> %g', store);
    fprintf('\n');
    %}
    % final result
    if step == persistence
        fprintf('%d is the smallest number terminated in %d steps!\n', n, step);
        break
    end
end


이제 max의 값을 1000으로, persistence의 값을 5로 설정한 후에 위 코드를 실행시켜 보면 아래의 결과를 얻는다.

>> 679 is the smallest number terminated in 5 steps!


이번에는 max의 값을 굉장히 크게 잡고, persistence의 값을 1부터 8까지 변화시키면서 위 코드를 반복 실행시켜 보았다. persistence 의 값이 8일때 코드를 실행하면 결과를 얻는데 1분 가량이 걸려서 그 뒤로는 확인해 보지 않았다. 결과는 아래와 같다.

>> 10 is the smallest number terminated in 1 steps!
>> 25 is the smallest number terminated in 2 steps!
>> 39 is the smallest number terminated in 3 steps!
>> 77 is the smallest number terminated in 4 steps!
>> 679 is the smallest number terminated in 5 steps!
>> 6788 is the smallest number terminated in 6 steps!
>> 68889 is the smallest number terminated in 7 steps!
>> 2677889 is the smallest number terminated in 8 steps!


  1. 숫자의 지속성이란 주어진 수의 각 자릿수들을 곱하여 두번째 수를 만들고, 다시 두번째 수의 각 자릿수들을 곱하여 세번째 수를 만들고... 하는 과정을 반복하여, 주어진 곱의 결과가 한자리의 수가 될 때까지 반복한 이 과정의 횟수를 말한다. 예를 들어 77은 네 단계를 거쳐서 77 → 49 → 36 → 18 → 8 과 같이 한자리 수가 되므로, 지속성 4를 가진다. [본문으로]
  2. [참고] http://www.mathworks.com/matlabcentral/newsreader/view_thread/246172 [본문으로]


  ::  
  • 공유하기  ::