Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jingyang-li/f6a472cfb724e7a14035d7321ea5c8cc to your computer and use it in GitHub Desktop.
Save jingyang-li/f6a472cfb724e7a14035d7321ea5c8cc to your computer and use it in GitHub Desktop.
T-SQL function to check Kaprekar number
create or alter FUNCTION [dbo].[kaprekar](@n int)
RETURNS bit
AS
BEGIN
DECLARE @result bit;
Begin
If exists (
select 1
from
(select @n number, square_value,
Cast(left(square_value,sq_len-n ) as int) number_left
,Cast(stuff(square_value,1,(sq_len-n ),'') as int) number_right
from (
Select @n number, len(square(@n)) sq_len
,square(@n) square_value )t
Cross apply (Select Number FROM master.dbo.spt_values
where type='P' and Number >=1 and Number <=1000 and Number< len(square(@n)) ) d(n)
) t
where number_left+number_right=number
)
Select @result=1
else
Select @result=0
End
RETURN @result;
END;
/*
select [dbo].[kaprekar](9)
--9 45 55 99 297 703 999
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment