Ronnie
Ronnie

Reputation: 1

Help with computer math project

I need help making a program that would calculate 1+x+x^2+...+x^n for a given x and a positive integer n and use it to calculate (1+x+x^2+...+x^10)(1+x^2+x^2...+x^10) for x=100

so far i have

def myfunc(x, n, step): 
  if n > 0: 
    return x**n + myfunc(x, n - step, step) 
  return 1 #In case n is 0

I would then use myfunc(100,10, 1)*myfunc(100,10,2) to get the answer. However, i have been recently informed that the function shouldn't contain any variable and should calculate the answer without putting any variables. So for example, it would be myfunc() and would calculate the same answer. How should I change my program so that it would still calculate the same answer?

Upvotes: 0

Views: 177

Answers (2)

Alexandre C.
Alexandre C.

Reputation: 56956

Hint, since the "functional-programming" tag is present, I assume it is an exercise in recursion:

1 + x + x**2 + ... + x**n = 1 + x * (1 + x + ... + x**(n-1))

You only need n multiplications and no exponentiation to evaluate this polynomial. This is called the Horner scheme. Note that this formula can also be implemented in a for loop: try to compute the value of 1 + ... + x^n with a pen and paper, using only n multiplications and deduce the algorithm.

Another hint, depending on what your teacher/advisor/mom wants:

1 + x + ... + x**n = (x**(n+1) - 1) / (x - 1).

Upvotes: 6

loosecannon
loosecannon

Reputation: 7803

def calc(x, n, step): 
  if n > 0: 
    return x**n + calc(x, n - step, step) 
  return 1 #In case n is 0

def myfunc()
  return calc(100,10,1)*calc(100,10,2)

to hard code the numbers in that would be the only way to get the answer with out supplying arguments,

Upvotes: 0

Related Questions