-- =============================================
--Author: <maco_wang>
--Create Date: <2011-01-21>
--Description: < decomposition of a positive integer into M 2 of N-th square and >
-- =============================================
Go
--Create a function
CREATE function getsumsequence (@num INT)
Returns nvarchar (200)
As
BEGIN
DECLARE @numc INT
SET @numc = @num
DECLARE @numstr VARCHAR (50)
SET @numstr = ' '
while (@num <> 0)
BEGIN
SET @numstr = @numstr + CONVERT (CHAR (1), @num% 2)
SET @num = @num/2
END
--select REVERSE (@numstr)
DECLARE @i INT
SET @i = LEN (@numstr)
DECLARE @j VARCHAR (MAX)
SET @j = "
while (@i > 0)
BEGIN
IF (SUBSTRING (REVERSE (@numstr), LEN (@numstr)-@i + 1, 1) = ' 1 ')
SELECT @j = @j + ' +2^ ' + CAST (@i-1 as VARCHAR (10))
SET @i = @i-1
END
Return (CAST (@numc as VARCHAR) + ' = ' + STUFF (@j, 1, 1, '))
END
Go
--Test example
SELECT dbo. Getsumsequence (12)
SELECT dbo. Getsumsequence (65)
SELECT dbo. Getsumsequence (892)
SELECT dbo. Getsumsequence (1919191)
--Running results
/*
12=2^3+2^2
65=2^6+2^0
892=2^9+2^8+2^6+2^5+2^4+2^3+2^2
1919191=2^20+2^19+2^18+2^16+2^14+2^11+2^7+2^6+2^4+2^2+2^1+2^0
*/
The decomposition of a positive integer into M 2 of N-th square and