简体   繁体   中英

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. For example:

Input : 10 2 N=10, M=2
Then output is : 10 + 5 + 2 + 1 + 1 because
first the given 10 (N) items are marked, then all of the 10 are exchanged for 5 new ones (N/M) and marked,
then 4 of these exchanged(1 saved for future) for 2 new ones and marked,
then 2 exchanged for 1 new one, this new one marked and
along with the 1 saved before exchanged for a new one and marked.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM