Skip to content

Instantly share code, notes, and snippets.

@kuoe0
Created December 14, 2013 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuoe0/7958688 to your computer and use it in GitHub Desktop.
Save kuoe0/7958688 to your computer and use it in GitHub Desktop.
check integer divisible by 3 using alternative sum
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2013 KuoE0 <kuoe0.tw@gmail.com>
#
# Distributed under terms of the MIT license.
"""
"""
def alt_add_digits_recursion(x, sign):
if x > 1:
return alt_add_digits(x >> 1, sign * -1) + (x & 1) * sign
return (x & 1) * sign
def alt_add_digits_iteration(x):
ret = 0
sign = 1
while x > 1:
ret = ret + (x & 1) * sign
x = x >> 1
sign = sign * -1
return ret
def alt_add_digits_iteration_no_mul(x):
ret = 0
sign = True
while x > 1:
ret = ret + (x & 1) if sign else ret - (x & 1)
x = x >> 1
sign = not sign
return ret
def divisible_3(x):
while x > 1:
x = alt_add_digits_iteration_no_mul(x)
x = x if x >= 0 else -x
return x == 0
if __name__ == "__main__":
import sys
for i in range(int(sys.argv[1])):
print i, divisible_3(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment