- Published on
[PS] n-th system game
- Authors
- Name
- 신주용
Programmers: n-th system game
Conditions
- The base
n
, the numbers to be obtained in advancet
, the number of participants in the gamem
, and the sequencep
are given. - The number
t
that must be spoken is displayed in sequence without spaces. - 10~15 are printed as capital letters A~F respectively.
- Changes from 0 to
n
base and creates a string that continues with the value. - Since
t
is required, if the length of thegame
string is longer that , the process of converting ton
base stops. - The -th character is concatenated until the length of
answer
becomest
.
Brute force
def solution(n, t, m, p):
answer = ''
num = 0
game = ""
while True:
numToN = convertN(num, n)
game += numToN
if len(game) > (t * m + p):
break
num += 1
for i in range(len(game)):
if i % m == p - 1:
answer += game[i]
if len(answer) == t:
break
return answer
def convertN(num, n):
if num == 0:
return '0'
digit = "0123456789ABCDEF"
temp = ""
while num:
q, r = divmod(num, n)
temp = digit[r] + temp
num = q
return temp
- Max: Test 16 〉 Pass (37.41ms, 10.7MB)
Big-O notation
- In
convertN()
, the while statement is repeated times. Expanding this,convertN()
is . - However, the actual time required for
convertN()
is 1 whennum
is 0, 1 when 1, 1 when 2, 2 when 3, 2 when 4 ... increases in logscale in this way. Therefore, the time taken for the while statement is the sum of these values. It will be less than , so it will be roughly close to . - The for statement that makes
answer
works as much as . - As a result, it operates at time.
Optimization
def convertN(num, n):
if num == 0:
return '0'
digit = "0123456789ABCDEF"
temp = ""
while num:
num, r = divmod(num, n)
temp = digit[r] + temp
return temp
- It's a small difference, but don't have to use
q
.
def solution(n, t, m, p):
answer = ''
num = 0
game = ""
targetLen = t * m + p
while len(game) < targetLen:
game += convertN(num, n)
num += 1
for i in range(len(game)):
if i % m == p - 1:
answer += game[i]
if len(answer) == t:
break
return answer
- Removed
numToN
because it is not necessary to use it. - Even does not need to be calculated every time.
- If you change the condition of the while statement, you can also remove the if statement.
- Max: Test 15 〉 Pass (36.15ms, 10.9MB)
Remember
- It would be good to remember how to convert the base system.
- In
divmod(a, b)
, whena
is 0,q
was not returned. Caution.