I've been thinking about making an Equation Solving program, starting off with some basic Equations first.
I have this Arithmetic progression problem here
Problem Statement: If the nth term of AP is 3n + 2 find the sum up to 15 terms
This is what I have tried,
n = 1
while n <= 15:
ap = 3 * n + 2
n += 1
print(ap)
#OUTPUT: 47
Is there a more efficient way to calculate these types of problems using python?
I'm thinking of handling bigger equations And the answer is not quite Correct
-
2The more efficient way to perform this task is to come up with a closed-form solution to the problem - a formula for the summation - using math. What you wrote is already the best you can do with a naive approach.mackorone– mackorone2022年01月22日 07:52:26 +00:00Commented Jan 22, 2022 at 7:52
-
2Why is there a loop here? print(3 * 15 + 2) would suffice.jackal– jackal2022年01月22日 07:56:19 +00:00Commented Jan 22, 2022 at 7:56
-
if you are looking for very fast math and nothing else, then using C/C++ is much faster than python, but if you have some math that you must do fast in a python program, then consider using cython or numba to speed up the calculation.Ahmed AEK– Ahmed AEK2022年01月22日 07:58:15 +00:00Commented Jan 22, 2022 at 7:58
-
Define "these types of problems".Kelly Bundy– Kelly Bundy2022年01月22日 08:01:43 +00:00Commented Jan 22, 2022 at 8:01
-
U could use lambda functions ?PSR– PSR2022年01月22日 08:08:57 +00:00Commented Jan 22, 2022 at 8:08
3 Answers 3
If you want the sum of 3n+2 for 1<=n<=15 then:
print(sum(3*n+2 for n in range(1,16)))
Output:
390
answered Jan 22, 2022 at 7:58
jackal
29.1k3 gold badges10 silver badges28 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
you can use the closed formula for arithmetic sequence
def fn(n):
return 3*(n*(n+1)//2) + 2*n
answered Jan 22, 2022 at 8:03
Tomáš Šturm
5395 silver badges9 bronze badges
Comments
ap = 0
for n in range(1,16):
ap += 3 * n + 2
print(ap)
S.B
17.1k12 gold badges38 silver badges74 bronze badges
1 Comment
Jeremy Caney
Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?
lang-py