Kaprekars Constant

From ZCubes Wiki
Jump to navigation Jump to search

Kaprekar's constant

The number 6174 is known as Kaprekar's constant[| Kaprekar's Constant 6174] after the Indian mathematician D. R. Kaprekar. This number is renowned for the following rule:

Take any four-digit number, using at least two different digits (leading zeros are allowed). Arrange the digits in descending and then in ascending order to get two four-digit numbers, adding leading zeros if necessary. Subtract the smaller number from the bigger number. Go back to step 2 and repeat.

Video: https://www.youtube.com/watch?v=xtyNuOikdE4

z^3 Solution

1001..1010@kc;
function kc(x)
{
	k=x.⁋.⪡.⋰;
	kp:=k.⋱.⚯*1 -k.⋰.⚯;
	_y=k;
	var r=-1, rt=-1,rs=[];	
	(1..8)@(
		function(i)
		{
			var t=kp(_y)
			
			if(t==6174 && r==-1)
			{
				r=i;rt=t;rs.push(t);
				throw("EXIT")
			}
			else
			{
				rs.push(t)
			}
			_y=t.⁋.⪡;
		}
	);
	☝;
	return([x,r,rs])	
}

x kc
1001
1001
4
1089 9621 8352 6174



1002
1002
3
2088 8532 6174



1003
1003
3
3087 8352 6174



1004
1004
7
4086 8172 7443 3996 6264 4176 6174



1005
1005
7
5085 7992 7173 6354 3087 8352 6174



1006
1006
7
6084 8172 7443 3996 6264 4176 6174



1007
1007
3
7083 8352 6174



1008
1008
3
8082 8532 6174



1009
1009
4
9081 9621 8352 6174



1010
1010
4
1089 9621 8352 6174



Notes

In Loops (such as 1..7),

throw("EXIT")

or

throw("BREAK")

will break the FOR loop.

throw("CONTINUE")

will continue the FOR loop call.

In the code above, the throw("EXIT") is used to go break the loop as the loop has reached 6174 potentially.

Also note the elegant way to handle exceptions. For example, tryx or ☝; is a quick way to wrap the previous block or statement with a try{}catch(){} statement.