Question: Optimise partial sum calculation I want to calculate partial sums for different parameters a, n: I also know that all partial sums I will need
Optimise partial sum calculation
I want to calculate partial sums for different parameters a, n:
I also know that all partial sums I will need to calculate are less or equal to 1018.
I tried the code with the sum calculation formula:
if __name__ == '__main__': n, a = map(int, input().split()) if a != 1: a_n1 = a ** (n + 1) res = (n * a ** (n + 2) - a ** (n + 1 * (n + 1) + a) // (a - 1) ** 2 else: res = sum([i for i in range(n + 1)]) print(round(res))
however it increases the memory limit of 256 Mb (the straight sum calclulation increases a time limit of 1sec).
Could you please help me optimise the code in python, so it takes less memory (I don't have an option of using numpy, etc.)
Thanks
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
