Tuesday, November 25, 2014

Write recursive t-sql code to get Square root of integer number without using SQRT function

Create Function [dbo].[fn_SQRT](@v_Number bigint,@v_ID bigint)
Returns bigint
as
Begin
If (@v_Number != 1)
Begin
if (@v_Number%@v_ID = 0)
Begin
Set @v_Number = @v_Number/(@v_ID * @v_ID)

return @v_ID * dbo.fn_SQRT(@v_Number, @v_ID)
End
Else
Begin
return dbo.fn_SQRT(@v_Number, @v_ID + 1)
End
End
return 1
End
GO

select [dbo].[fn_SQRT](63297936, 2)
Go

--> 7956

Monday, November 24, 2014

Write t-sql code to generate Fibonacci series without using any inbuilt function

Declare @v_Number INT = 158919851
Declare @v_First INT = 0
Declare @v_Second INT = 1
Declare @v_Temp INT

Print @v_First

While(@v_Second < @v_Number)
Begin
    Set @v_Temp = @v_First + @v_Second
    Set @v_First = @v_Second
    Set @v_Second = @v_Temp

    Print @v_First
End

Write t-sql code to check if given number is Palindrome or not without using any inbuilt function

Declare @v_ActualNumber INT = 158919851
Declare @v_ReverseNumber INT = 0
Declare @v_TempNumber INT
Declare @v_Number INT

Set @v_TempNumber = @v_ActualNumber

While(@v_TempNumber > 0)
Begin
    if (@v_TempNumber >= 10)
    Begin
        Set @v_Number = @v_TempNumber%10

        Set @v_ReverseNumber = @v_ReverseNumber + @v_Number

        Set @v_TempNumber = (@v_TempNumber - @v_Number)/10

        Set @v_ReverseNumber = @v_ReverseNumber * 10
    End
    Else
    Begin
        Set @v_ReverseNumber = @v_ReverseNumber + @v_TempNumber

        Set @v_TempNumber = 0
    End
End

if (@v_ActualNumber = @v_ReverseNumber)
Begin
    Print 'Palindrome Number'
End
Else
Begin
    Print 'Not Palindrome Number'
End

Write t-sql code to get Square root of integer number without using SQRT function

Declare @v_ActualNumber INT
Declare @v_FinalSquareRootNumber INT
Declare @v_SquareRootNumber INT
Declare @v_ID INT

Set @v_ActualNumber = 63297936
Set @v_FinalSquareRootNumber = 1
Set @v_ID = 2

While(@v_ActualNumber <> 1)
Begin
    if (@v_ActualNumber%@v_ID = 0)
    Begin
        Set @v_SquareRootNumber = @v_ID

        Set @v_ActualNumber = @v_ActualNumber/(@v_SquareRootNumber * @v_SquareRootNumber)

        Set @v_FinalSquareRootNumber = @v_FinalSquareRootNumber * @v_SquareRootNumber
    End
    Else
    Begin
        Set @v_ID = @v_ID + 1
    End
End

Select @v_FinalSquareRootNumber