MySQL Forums
Forum List  »  Microsoft SQL Server

kaprekar number check function not working on T-SQL
Posted by: Святослав Тарадай
Date: May 08, 2022 10:22AM

Hi! i made an T-SQL Function which checks if a number is a kaprekar number or not. here is the code

```
CREATE FUNCTION [dbo].[kaprekar](@n int)
RETURNS bit
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @result bit;
DECLARE @sq_n INT;
DECLARE @count_digits INT;
DECLARE @r_digits INT;
DECLARE @eq_parts INT;
DECLARE @sum INT;

SET @sq_n = @n * @n;
SET @count_digits=0;
WHILE @sq_n <> 0
BEGIN
SET @count_digits= @count_digits + @count_digits;
SET @sq_n=@sq_n/10;
END;
SET @sq_n = @n*@n;

WHILE @r_digits<@count_digits
BEGIN
SET @eq_parts=POWER(10,@r_digits);
SET @sum = @sq_n/@eq_parts + @sq_n% @eq_parts;
END;


IF @n = 1
BEGIN
SET @result=1;
END;
ELSE IF @eq_parts = @n
BEGIN
SET @result=0;

END;
ELSE IF @sum=@n
BEGIN
SET @result=1;

END;
ELSE
BEGIN
SET @result=0;
END;

RETURN @result;
END;

```

but it doesn't work. it only works with the number 1, not every other one. the inspection i made showed that the problem is the main part of code, not with the IF ELSE block. Can you help me?

Options: ReplyQuote




Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.