예제 #1
0
def factor1(target):
    start_time = time()
    num_states = 1

    if not isinstance(target, IntegerBase2):
        target = IntegerBase2(target)

    key_func = partial(lambda x, target: target.as_int - x.as_int, target=target)
    frontier = BinarySearchTree(key_func)

    num_digits = target_to_max_factor_num_digits(target, 0)
    for i, j in itertools.combinations_with_replacement(xrange(BASE), 2):
        p_digits = [0 for _ in xrange(num_digits)]
        q_digits = [0 for _ in xrange(num_digits)]
        p_digits[-1] = i
        q_digits[-1] = j
        _prod = Product(p_digits, q_digits)
        frontier.insert(_prod)

    solved = False

    while len(frontier):

        candidate = frontier.pop_min()

        #print
        #print IntegerBase2.from_int(target)
        #print candidate
        #from time import sleep
        #sleep(1)

        children = candidate.generate_children()
        for child in children:
            if child.as_int > target.as_int:
                continue
            elif child.as_int == target.as_int:
                print 'Solution!', child
                solved = True
                break
            else:
                frontier.insert(child)
                num_states += 1

        if solved:
            break

    end_time = time()
    print 'States checked:', num_states
    print 'Time taken: {:.2f}s'.format(end_time - start_time)
예제 #2
0
def factor1(target):
    start_time = time()
    num_states = 1

    if not isinstance(target, IntegerBaseFixed):
        target = IntegerBaseFixed(target)

    key_func = partial(product_to_error, target=target)
    frontier = BinarySearchTree(key_func)

    for i, j in itertools.combinations_with_replacement(xrange(BASE), 2):
        frontier.insert(ProductFixed(i, j))

    solved = False
    while len(frontier):

        candidate = frontier.pop_min()

        #print
        #print IntegerBaseFixed.from_int(target)
        #print candidate
        #from time import sleep
        #sleep(1)

        if candidate.as_int() == target:
            print 'Solution!', candidate
            break

        children = candidate.generate_children()
        children = filter_digit_length(children, target)
        children = filter_correct_digits(children, target)

        for child in children:
            frontier.insert(child)
        num_states += len(children)

        if not num_states % 10000:
            print 'Checked:', num_states

    end_time = time()
    print 'States checked:', num_states
    print 'Time taken: {:.2f}s'.format(end_time - start_time)