[英]Speed up code in python
N,M are taken as input, N items are given initially, these may be marked and exchanged for new ones, such that 1 new item is given for M of these marked items, the problem is to find the maximum number of items that can be marked in this way. N,M作为输入,最初给出N个项目,可以标记这些项目并交换为新的项目,这样,对于M个这些标记项目给出了1个新项目,问题是要找到可以容纳的最大项目数以这种方式被标记。 For example: 例如:
Input : 10 2
N=10, M=2 输入: 10 2
N = 10,M = 2
Then output is : 10 + 5 + 2 + 1 + 1
because 然后输出为: 10 + 5 + 2 + 1 + 1
因为
first the given 10 (N) items are marked, then all of the 10 are exchanged for 5 new ones (N/M) and marked, 首先标记给定的10(N)个项目,然后将这10个项目全部换成5个新项目(N / M)并标记,
then 4 of these exchanged(1 saved for future) for 2 new ones and marked, 然后将其中4个交换(另存1个以备将来使用)换成2个新标记,
then 2 exchanged for 1 new one, this new one marked and 然后2换成1个新的,这个新的标记为
along with the 1 saved before exchanged for a new one and marked. 连同保存的1交换为新的1并标记。
Constraints:
1 <= N <= 1000
2 <= M <= 1000
This is what i tried: 这是我尝试的:
n,m = map(int,raw_input().split())
s = n
aux = 0
while n!=1:
aux = n%m
n /= m
s +=n
n +=aux
print s
But it is too slow to get past the judge. 但是,要通过法官实在太慢了。 How can I speed it up? 我如何加快速度? Any other algorithms to do this? 还有其他算法可以做到这一点吗?
n,m = map(int,raw_input().split())
s = n
aux = 0
while n>=m:
n, aux = divmod(n, m)
s +=n
n +=aux
print s
The termination condition of the loop was wrong and should be current value < m as we cannot get new items of we have lees than M marked items left with us. 循环的终止条件是错误的,并且应为当前值<m,因为我们无法获得新的物品,因为我们拥有的酒糟比剩下的M个标记物品更糟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.