Given positive, integer N, what does this algorithm produce?
let S and D = N
repeat
let D = ⌊D/2⌋
subtract D from S
until D=0
produce S as the result
Note: ⌊
x⌋ represents the integer part of
x.
For non-programmers: start with a positive, integer number (say, 19). Divide it by 2, discarding remainders, until you get to 0. (In this case, you'd get 9, 4, 2, and 1.) Sum all the quotients. (9+4+2+1=16.) Subtract the sum from the original number. (19-16=3.) What's the result?
Here's an implementation. It actually does a little more, as it loops through and shows the results for several values of N.
CLS
FOR n = 1 TO 40
s = n: d = n
DO
d = INT(d / 2)
s = s - d
LOOP UNTIL d = 0
PRINT USING "## ## "; n; s
NEXT
Resulting in:
1 1
2 1
3 2
4 1
5 2
6 2
7 3
8 1
9 2
10 2
11 3
12 2
13 3
14 3
15 4
16 1
17 2
18 2
19 3
20 2
21 3
22 3
23 4
24 2
25 3
26 3
27 4
28 3
29 4
30 4
31 5
32 1
33 2
34 2
35 3
36 2
37 3
38 3
39 4
40 2
|
Posted by Charlie
on 2005-01-14 15:16:49 |