A program to add the first "n" elements of a progression geometric, given the first element "a0" and the ratio "r" between the elements. For example, for n = 7, a0 = 1, r = 3: 1 + 3 + 9 + 27 + 81 + 243 + 729 = 1093
A program to add the first "n" elements of a progression geometric, given the first element "a0" and the ratio "r" between the elements. For example, for n = 7, a0 = 1, r = 3: 1 + 3 + 9 + 27 + 81 + 243 + 729 = 1093
Mathematics [O (1)]
The general term of an arithmetic progression is given by:
Inthisway,thesumofthenfirsttermswouldbe:
That,ifweapplythegeneralterm,weobtainequation(1):
Ifwemultiplybothsidesbytheratio,q,wehaveequation(2):
Ifwesubtracttheequations(2)and(1)fromeachother,wewillhave:
Whatcanbesimplifiedto:
Therefore,thefunctionthatreturnsthesumofntermsofanarithmeticprogressiondescribedbytheinitialtermto1andtheqis:
defsoma_progressao_aritmetica(n,a1,q):returna1*(q**n-1)/(q-1)
Seeworkingat Repl.it | Ideone | GitHub GIST
To call it, it would suffice:
print(soma_progressao_aritmetica(n=7, a1=1, q=3)) # 1093.0
Repeat loop [O (n)]
Another way would be to use the sum
native function, along with a generator inline , which basically calculates all n terms of the progression and sums. >
def soma_progressao_aritmetica(n, a1, q):
return sum(a1*q**i for i in range(n))
Obtaining the same result, however, is a solution that has time performance O (n); that is, the execution time of the function will be directly proportional to the number of terms added, while the first solution will not.
I'm studying Python and programming a few weeks, but I've tried to come up with a solution. I do not know if it's the best code, but it works.
n = int(input("Informe quantos elementos irá somar na PG: "))
r = float(input("Informe a razão entre os elementos: "))
primeiroelemento = float(input("Informe o primeiro elemento: "))
total = 0
pg = 1
print("Os termos da progressão são: ")
print(primeiroelemento)
for i in range(1, n):
pg = pg * r
print(pg)
total = total + pg
print("O total da PG é: ", total+primeiroelemento)