Created
May 8, 2022 19:06
-
-
Save jingyang-li/f6a472cfb724e7a14035d7321ea5c8cc to your computer and use it in GitHub Desktop.
T-SQL function to check Kaprekar number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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