0

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

asked Jan 22, 2022 at 7:49
5
  • 2
    The 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. Commented Jan 22, 2022 at 7:52
  • 2
    Why is there a loop here? print(3 * 15 + 2) would suffice. Commented 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. Commented Jan 22, 2022 at 7:58
  • Define "these types of problems". Commented Jan 22, 2022 at 8:01
  • U could use lambda functions ? Commented Jan 22, 2022 at 8:08

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0
ap = 0
for n in range(1,16):
 ap += 3 * n + 2
print(ap)
S.B
17.1k12 gold badges38 silver badges74 bronze badges
answered Jan 22, 2022 at 10:13

1 Comment

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?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.