Created
November 1, 2010 01:01
-
-
Save PJensen/657406 to your computer and use it in GitHub Desktop.
Unoptimized solution for Problem-74.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
## | |
# @Fle: p74.py | |
# @Author: PJensen | |
# @Version: Oct 31, 2010 | |
# @Description: Unoptimized solution for Problem-74. | |
# http://projecteuler.net/index.php?section=problems&id=74 | |
# n-factorial | |
def n_fact(n): | |
n_result = 1 | |
for index in range(1, n + 1): | |
n_result *= index | |
return n_result | |
# n-factorial digit sum | |
def fact_digit_chain_sum(gen): | |
def fact_digit_chain(n): | |
for c in str(n): | |
yield n_fact(int(c)) | |
return sum(fact_digit_chain(gen)) | |
# generate the full non-repeating sequence | |
# but do not return the full chain | |
def fact_digit_chain_seq_len(n): | |
c = [n]; current = fact_digit_chain_sum(n) | |
while current not in c: | |
c.append(current); | |
current = fact_digit_chain_sum(current); | |
return len(c) | |
# assertion as to the chain length of 69 | |
assert((fact_digit_chain_seq_len(69) == 5)) | |
# declare constant max and start time | |
N_MAX = 1000000; tStart = time.time() | |
# lc that generates all chains w/ length 60 for generators up to N_MAX | |
chains_with_length_60 = [x for x in range(1, N_MAX) if fact_digit_chain_seq_len(x) == 60] | |
# show that exact number that meet the above criterion. | |
print ('chains of length 60 from 0 to %s: %s, calculated in %s') %\ | |
(N_MAX, str(len(chains_with_length_60)) ,time.time() - tStart) |
Optimizations:
1) Solution is a *very* good candidate for memoization.
2) Since **n_fact(n):** works on the unit digits [0, 9] skip computation return hard-coded factorial.
3) In-lining of functions.
4) Remove iterator in favor of straight function.
Note: (2), (3) and (4) yield a 30% improvement, leaving running time around 738.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
chains of length 60 from 0 to 1000000: xxxxx, calculated in 1053
(took ~17 minutes to complete, revise to get solution under 1 the minute mark)