Skip to content

Instantly share code, notes, and snippets.

@anuvrat
Created January 11, 2017 08:05
Show Gist options
  • Save anuvrat/b705831c7f6c9ac71310f9c9f0cd66b4 to your computer and use it in GitHub Desktop.
Save anuvrat/b705831c7f6c9ac71310f9c9f0cd66b4 to your computer and use it in GitHub Desktop.
class memoize(dict):
def __init__(self, func):
self.func = func
def __call__(self, *args):
return self[args]
def __missing__(self, key):
result = self[key] = self.func(*key)
return result
@memoize
def count_ways(num, current_multiple, occurrences):
if num == 0: return 1
else:
count = 0
if occurrences == 0:
next_multiple, next_occurrences = 1, 1
elif occurrences == 1:
next_multiple, next_occurrences = current_multiple, 2
else:
next_multiple, next_occurrences = current_multiple << 1, 1
while num - next_multiple >= 0:
count += count_ways(num - next_multiple, next_multiple, next_occurrences)
next_multiple, next_occurrences = next_multiple << 1, 1
return count
if __name__ == "__main__":
num = int(input().strip())
if num == 0: print(0)
else: print(count_ways(num, 0, 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment