The decomposition of a positive integer into M 2 of N-th square and

Source: Internet
Author: User

-- =============================================

--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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.