Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

Kaprekar Steps | Code challenge MATLAB

6174 is the Kaprekar constant. All natural numbers less than 10,000 (except some with same digits) can be reduced to 6174 in the following steps:
Order the digits of the number in descending and ascending order and compute the difference. Repeat the process till you get 6174.
Your code should return the number of Kaprekar steps for a given input.

For example, choose 3524:
5432 – 2345 = 3087
8730 – 0378 = 8352
8532 – 2358 = 6174

Output: 3

For detail explanation, check this:
https://en.wikipedia.org/wiki/6174_%28number%29

Code:

x=input('Enter the number:');
m=x;
c=0;
while(m~=6174)
    m=Kaprekar(m);
    c=c+1;
end
disp(c);



Function:

function a=Kaprekar(x)
g=x;
Y=[];
while(g>0)
 b=rem(g,10);
 Y=[Y b];
 g=(g-b)/10;
end
Sa=sort(Y);
p=0;
for i=1:length(Sa)
    p=10*p+Sa(i);
end
ks=0;
Ma=fliplr(sort(Y));
for i=1:length(Ma)
    ks=10*ks+Ma(i);
end
a=ks-p;
end

Explanation:


Reference Video:



No comments

Popular Posts