有N个小朋友围坐成一圈,老师给每个小朋友随机发偶数个糖果,然后进行下面的游戏:
每个小朋友都把自己的糖果分一半给左手边的孩子
一轮分糖后,拥有奇数颗糖的孩子由老师补给1个糖果,从而变成偶数
反复进行这个游戏,直到所有小朋友的糖果数都相同为止
问,在已知的初始糖果情形下,老师一共需要补发多少个糖果
DECLARE @I INT
DECLARE @N INT
DECLARE @M INT
SELECT number,CRYPT_GEN_RANDOM(2)%50*2 AS V INTO #tmp
FROM master..spt_values WHERE type='P' AND number BETWEEN 1 AND 100
SELECT TOP 0 * INTO #Rst FROM #tmp
SELECT @N=SUM(V) FROM #tmp
SET @I=0
WHILE 1=1
BEGIN
INSERT INTO #rst
SELECT * FROM #tmp WHERE V%2=0
UPDATE a SET v=a.v/2
FROM #tmp a INNER JOIN #Rst b ON b.number = a.number
UPDATE a SET v=a.V+b.v/2
FROM #tmp a INNER JOIN #Rst b ON b.number = a.number+1 OR (a.number=100 AND b.number=1)
UPDATE #tmp SET V=v+1 WHERE v%2=1
SET @I=@I+1
TRUNCATE TABLE #Rst
IF (SELECT COUNT(DISTINCT V) FROM #tmp)=1
BREAK
END
SELECT @M=SUM(V) FROM #tmp
SELECT @I AS Rst,@M-@N AS dif
DROP TABLE #tmp
DROP TABLE #rst