Sum recursive sequence

Asked

Viewed 469 times

0

I am implementing a recursive code that adds the following sequence: x + x 2 / 2 + x 3 / 3... x n / n, for this sum, I thought of a definition, combining two recursive functions, as follows below, but it is returning very high values, to n > 3.

def potencia(x, n):
    if n == 0: return 1
    else:
        return x * potencia(x, n - 1)

def Soma_Seq (x, n): 
    if n == 0: return 0
    else: 
        return x + Soma_Seq(potencia(x, n - 1), n - 1) / n

2 answers

1

Datum: Soma(x,n) = x + x^2 / 2 + x^3 / 3 + ... + x^n / n

Notice that:

Soma(x,n) = x + x^2 / 2 + x^3 / 3 + ... + x^n / n
#          |----------------------------|
Soma(x,n) =       Soma(x,n-1)           + x^n / n

defining that, for n=1: Soma(x, 1) = x

def potencia(x, n):
    return (x**n)

def Soma_Seq (x, n): 
    if n == 1: return x
    else: 
        return Soma_Seq(x, n-1) + potencia(x, n)/n

We can also write the function potencia() recursively as follows:

def potencia(x, n):
    if n == 1: return x
    else:
        return x * potencia(x, n-1)

0

We can use this answer to your question:

Recursive function simulating a number elevated to a power

def potencia(base, power, show_steps=True):
    """show_steps serve só para dizer 
    se amostrar os passos recursivos escritos ou não."""
    if power == 0: # caso base
        if show_steps:
            print(base, "^{0} = 1", sep="")        
        return 1
    else: # passo recursivo
        if show_steps:
            print(base, "^{", power, "} = ", base, " * ", base, "^{", power - 1, "}", sep="")
        return base * potencia(base, power - 1, show_steps)

def Soma_Seq (x, n): 
    if n == 0: return 0
    else: 
        return x + Soma_Seq(potencia(x, n - 1), n - 1) / n

I believe it’s a good starting point.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.