Skip to content
This repository has been archived by the owner on Feb 23, 2021. It is now read-only.

Commit

Permalink
Added solution for Problem #16
Browse files Browse the repository at this point in the history
Moved common functions from solutions 4 and 16 into lib/digits.py, which
has a function that returns a list containing the digits of an input number.
  • Loading branch information
Anks committed Dec 15, 2008
1 parent 5c50dfd commit 5d3d29e
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 8 deletions.
15 changes: 7 additions & 8 deletions 004/4.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, math
sys.path.append('../lib')
from digits import get_digits

"""
I’m trying a very brute force approach here. There probably is a way to this
algebraically, not numerically.
"""

def is_palindrome(number):
""" Return true if the number is a palindrome.
Start dividing the number by 10, 100, 1000, etc to get the digits
from the right-hand side of the number.
"""
digits = []
divisor = 10.0
while number * 10 / divisor > 0.1:
remainder = number % divisor
digits.append(remainder / (divisor / 10)) # Find the first digit of this number
number = number - remainder # Round-up the number so that there is no extra remainder
divisor = divisor * 10 # increase the divisor to get the next number

digits = get_digits(number)

palindrome = True
for (k, v) in zip(digits, reversed(digits)):
Expand Down
8 changes: 8 additions & 0 deletions 016/16.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
sys.path.append('../lib')
from digits import get_digits

print sum(reversed(get_digits(2 ** 1000)))
6 changes: 6 additions & 0 deletions 016/README.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Problem 16

2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^(1000)?

14 changes: 14 additions & 0 deletions lib/digits.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def get_digits(number):
""" Return the digits present in the number """
digits = []
divisor = 10
while number * 10.0 / divisor > 0.1:
remainder = number % divisor
digits.append(int(remainder / (divisor / 10))) # Find the first digit of this number
number = number - remainder # Round-up the number so that there is no extra remainder
divisor = divisor * 10 # increase the divisor to get the next number

return digits

0 comments on commit 5d3d29e

Please sign in to comment.