All about flooble | fun stuff | Get a free chatterbox | Free JavaScript | Avatars    
perplexus dot info

Home > Algorithms
Whadduzitdo? (Posted on 2005-01-14) Difficulty: 4 of 5
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?

See The Solution Submitted by e.g.    
Rating: 3.7143 (7 votes)

Comments: ( Back to comment list | You must be logged in to post comments.)
Solution Recursive solution | Comment 3 of 9 |
Let's call the output of the algorithm, f(N). Obviously, f(0)=0.

If we run the algorithm with N=x and N=2X, the answer is the same: on the second run, the first pass gets D=x, which is subtracted from S, that started with 2x and thus ends with x, so the second pass starts the same way as with N=x. This allows us to write f(2x)=f(x).

A similar analysis shows that f(2x+1)=1+f(x), so we are now looking for a function that satisfies:


f(0)=0

f(2x)=f(x)

f(2x+1)=1+f(x)


Thinking in binary, 0 has no ones in its representation; 2x has the same number of ones as x; 2x+1 has one more one than x... so the answer is f(x)=number of ONEs in the binary representation of x.
  Posted by Federico Kereki on 2005-01-14 17:33:10

Please log in:
Login:
Password:
Remember me:
Sign up! | Forgot password


Search:
Search body:
Forums (0)
Newest Problems
Random Problem
FAQ | About This Site
Site Statistics
New Comments (10)
Unsolved Problems
Top Rated Problems
This month's top
Most Commented On

Chatterbox:
Copyright © 2002 - 2017 by Animus Pactum Consulting. All rights reserved. Privacy Information