Project Euler 101 – Building polynomial functions based on first k terms of a sequence

by Rob on January 17, 2012

in Code Samples,Linear Algebra,Math,Project Euler

http://projecteuler.net/problem=101

#euler 101

# let's use numpy for our linear algebra matrix operations

import math

from numpy import *

# we'll use the array data structure for vectors, matrix
# multiplication, and inverses

#tenth polynomial generating function (and the test cube function)

def polyTerm(n):
    return int(1 - n + n*n - math.pow(n,3) + math.pow(n,4) - math.pow(n,5) + math.pow(n,6) - math.pow(n,7) + math.pow(n,8) - math.pow(n,9) + math.pow(n,10))

def cubethis(n):
    return n*n*n

poly = {}
for i in range(1, 11):
    poly[i] = polyTerm(i)

cube = {}
for i in range(1, 11):
    cube[i] = cubethis(i)

def matr(n):  # returns square matrix nxn
    output = []
    for i in range(n):   # i is rows
        temp = [int(math.pow(x+1, i)) for x in range(n)]
        output.append(temp)
    a = array(output).transpose()
    return a

def opCalc(n, sequence):  # takes n from 2 to length of sequence
    if n == 1:
        return sequence[1]
    else:
        m = matr(n)
        mI = linalg.inv(m)
        v = array([sequence[x] for x in range(1, n+1)])
        d = dot(mI, v)
        p = n+1
        pS = [int(math.pow(p, e)) for e in range(n)]
        return sum(d*pS)

answer = 0
for i in range(1, 11):
    temp = opCalc(i,poly)
    print i, temp
    answer += temp

print "the answer is ", int(answer)

Leave a Comment

Previous post:

Next post: