我正在练习解决以下问题。我在python 3中编写代码,已经在这里停留了很长时间。请帮助我优化代码
Akash对新函数F感兴趣,例如,
F(x) = GCD(1, x) + GCD(2, x) + ... + GCD(x, x)
其中GCD是最大公约数。 现在,问题很简单。给定大小为N的数组A,有两种查询类型: 1. CXY:计算F(A [X])+ F(A [X + 1])+ F(A [X + 2])+ .... + F(A [Y])(mod 10 ^ 9 + 7) 2. U X Y:更新数组A [X] = Y
的元素输入 输入的第一行包含整数N,即数组的大小。 下一行包含A个元素的N个空格分隔的整数。 下一行包含整数Q,即查询数量。 接下来的Q行包含两个查询之一。
Output:
For each of the first type of query, output the required sum (mod 10^9 + 7).
Constraints:
1 <= N <= 106
1 <= Q <= 105
1 <= Ai <= 5*105
For Update ,
1 <= X <= N
1 <= Y <= 5*105
For Compute ,
1 <= X <= Y <= N
SAMPLE INPUT
3
3 4 3
6
C 1 2
C 1 3
C 3 3
U 1 4
C 1 3
C 1 2
SAMPLE OUTPUT
13
18
5
21
16
Explanation
A[1] = 3, A[2] = 4, A[3] = 3
F(3) = GCD(1, 3) + GCD(2, 3) + GCD(3, 3) = 1 + 1 + 3 = 5.
F(4) = GCD(1, 4) + GCD(2, 4) + GCD(3, 4) + GCD(4, 4) = 1 + 2 + 1 + 4 = 8.
First query, the sum will be F(3) + F(4) = 5 + 8 = 13 (mod 10^9 + 7).
Second query, the sum will be F(3) + F(4) + F(3) = 5 + 8 + 5 = 18 (mod 10^9 + 7).
Third query, the sum will be F(3) = 5 (mod 10^9 + 7).
Fourth query will update A[1] = 4.
Fifth query, the sum will be F(4) + F(4) + F(3) = 8 + 8 + 5 = 21 (mod 10^9 + 7).
Sixth query, the sum will be F(4) + F(4) = 8 + 8 = 16 (mod 10^9 + 7).
import math
def ft(t):
s=0
for i in range(1,t+1):
s+=math.gcd(i , t)
#print(s)
return s
n=int(input())
a=list(map(int,input().split()))
q=int(input())
def f(a):
su =0
for i in range(1,a+1):
su+=math.gcd(i,a)
return su
for _ in range(q):
t = list(input().split())
t[1],t[2] = int(t[1]),int(t[2])
if t[0] == 'U':
a[t[1]-1] = t[2]
else:
#fq(t[1]-1,t[2]-1,a)
sm = 0
for i in range(t[1]-1,t[2]):
#print(i,a,f)
sm += f(a[i])
print(sm%(10**9+7))
I am getting time limit exceeded for majority of the test cases.How can i optimize the code.