1. 给一个数组,求,数组中的每个元素可由多少个素数组成,求总和。
注释部分代码超时了,优化后如下:
def test1():
n = int(input())
arr = list(map(int, input().strip().split(" ")))[:n]
res = 0
for i in range(n):
res += countPrime(arr[i])
return res
def countPrime(n):
if n < 2:
return 0
count = 0
count = n //2
# while n >= 2:
# n -= 2
# count += 1
return count
if __name__ == '__main__':
print(test1())
3. 给一个数组,求总和和。若是和中有数字“5”,则总和为零。保证符合要求的和最大。
思路:先求总和,之后依次判断总和中的元素是否有“5”,若存在5,将最小的元素弹出并累计弹出元素和。
def test3():
n = int(input())
arr = list(map(int, input().strip().split(" ")))
# n = 1
# arr = [5]
arr.sort(reverse=True)
count = 0
res = sum(arr)
tem = res
while tem > 0:
if tem % 10 == 5:
lastPop = arr.pop()
count += lastPop
if arr:
res = sum(arr) + count - lastPop
tem = res
continue
else:
return 0
tem = tem // 10
return res
if __name__ == '__main__':
res = test3()
print(res)