def find_residue(residue): p = {0: 1} pentagonal = [] pent_index = 1 found_match = False while not found_match: if pent_index > 0: next_index = -pent_index else: next_index = abs(pent_index) + 1 begin_val = polygonal_number(5, pent_index) end_val = polygonal_number(5, next_index) pentagonal.append(begin_val) for n in range(begin_val, end_val): # doesn't include end_val p[n] = 0 for index, val in enumerate(pentagonal): if (index / 2) % 2 == 0: p[n] = (p[n] + p[n - val]) % residue else: p[n] = (p[n] - p[n - val]) % residue if p[n] == 0: found_match = True return n pent_index = next_index raise Exception("Should not reach this line")
def all_polygonal(s, digits): result = [] for i in range(10 ** digits): curr = polygonal_number(s, i) if curr >= 10 ** (digits - 1): if curr < 10 ** digits: result.append(curr) else: break return result
def main(verbose=False): # Not only finds the minimum, but also checks to make sure # it is the smallest. Since P_j - P_k >= P_j - P_(j-1) = 3j - 2 # If 3j - 2 > D, then P_j - P_k > D, and we not longer need to # check the minimum pair = [1, 2] D = -1 while D == -1 or 3*pair[1] - 2 <= D: vals = [polygonal_number(5, val) for val in pair] difference = abs(vals[0] - vals[1]) if D != -1 and difference > D: # since increment decreases the first argument, if # we go past the difference, we can stop checking # [k, j] for a fixed j, and we just bypass # by incrementing j last = pair[1] pair = [last, last + 1] else: if reverse_polygonal_number(5, difference) != -1: if reverse_polygonal_number(5, sum(vals)) != -1: if D == -1 or difference < D: D = difference pair = increment_pair(pair) return D
def main(verbose=False): poly = polygonal_number(3, 100) return abs(sum_first_n_sq(100) - poly * poly)