Skip to content

Instantly share code, notes, and snippets.

@rmax
Created August 15, 2010 20:38
Show Gist options
  • Save rmax/525928 to your computer and use it in GitHub Desktop.
Save rmax/525928 to your computer and use it in GitHub Desktop.
"""
http://revista.python.org.ar/1/html/revista.html#desafio-python
entrada: 11
salida: 11
entrada: 8
salida 2^3
entrada: 24
salida 2^3 x 3
entrada: 168
salida 2^3 x 3 x 7
"""
from collections import defaultdict
def explode(n):
top = (n // 2) + 1
divs = defaultdict(int)
for i in range(2, top):
while n % i == 0:
n = n / i
divs[i] += 1
if divs:
parts = (["%d"%k, "%d^%d"%(k,v)][v>1] for (k,v) in divs.iteritems())
return " x ".join(parts)
else:
return str(n)
def main():
assert explode(11) == "11"
assert explode(8) == "2^3"
assert explode(24) == "2^3 x 3"
assert explode(168) == "2^3 x 3 x 7"
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment