์ตœ๋Œ€ 1 ๋ถ„ ์†Œ์š”

[๋ฐฑ์ค€-1010] ๋‹ค๋ฆฌ๋†“๊ธฐ Pythonํ•ด๋‹ต๊ณผ ์—๋Ÿฌ

๋ฐฑ์ค€/๋‹จ๊ฒŒ๋ณ„ ๋ฌธ์ œ/์กฐํ•ฉ๋ก /๋‹ค๋ฆฌ๋†“๊ธฐ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด์•˜๋‹ค.

์ค‘๋ณต์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ๋ฝ‘๊ธฐ ๋ผ๊ณ  ์ƒ๊ฐํ•ด์„œ ๊ฐ€์žฅ ๋จผ์ € ์ดํ•ญ๊ณ„์ˆ˜($_nC_r$)๋ฅผ ๋– ์˜ฌ๋ ธ๋‹ค.

์ฝ”๋“œ

์ •๋‹ต์ฝ”๋“œ

import sys

def m_C_n(n, m):
    up = 1
    down = 1

    for i in range(m, m-n, -1):
        up *= i
    for i in range(1, n+1):
        down *= i
    
    return round(up/down)
        
num = int(sys.stdin.readline())
result = []
for i in range(num):
    n, m = map(int, sys.stdin.readline().split())  

    result.append(m_C_n(n, m))

for i in range(num):
    print(result[i])

์—๋Ÿฌ์ฝ”๋“œ

def factorial(n):
    if n == 1:      
        return 1    
    return n * factorial(n-1)    

n = int(input())
m = int(input())

print(factorial(n)/(factorial(m)*factorial(n-m)))

์œ„ ์ฝ”๋“œ๋Š” ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
๊ธฐ์กด ๊ณต์‹์„ ์ ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ ํŒฉํ† ๋ฆฌ์–ผ ๊ณ„์‚ฐ๊ณผ ์žฌ๊ท€ ๋ฐฉ์‹์„ ์‚ฌ์šฉํ–ˆ๋Š”๋ฐ ์•„๋ž˜์™€ ๊ฐ™์€ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๊ฐ€ ์ถœ๋ ฅ๋˜๋ฉด์„œ ์‹คํ–‰์ด ์ค‘๋‹จ๋˜์—ˆ๋‹ค.

RecursionError: maximum recursion depth exceeded

์œ„ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด๋‚˜ ์‹œ์Šคํ…œ์—์„œ ํ—ˆ์šฉํ•˜๋Š” ์ตœ๋Œ€ ์žฌ๊ท€ ๊นŠ์ด(recursion depth)๋ฅผ ์ดˆ๊ณผํ–ˆ์Šต๋‹ˆ๋‹ค.๋ผ๋Š” ๋œป์œผ๋กœ, ์ž…๋ ฅ๊ฐ’์— ์˜ํ•œ ์žฌ๊ท€ ํšŸ์ˆ˜๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์œผ๋ฉด ์ €๋Ÿฐ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

ํ•ด๊ฒฐ ๋ฐฉ๋ฒ•์œผ๋กœ๋Š” ์žฌ๊ท€ ํ˜•์‹ -> ๋ฐ˜๋ณต๋ฌธ ํ˜•์‹๊ณผ, ์žฌ๊ท€ ํ˜ธ์ถœ์˜ ๋ฐ˜ํ™˜๊ฐ’์„ ์ €์žฅ ํ˜น์€ ์Šคํƒ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ• ๋“ฑ์ด ์žˆ๋‹ค.

์ดํ•ญ๊ณ„์ˆ˜($_nC_r$)๋ž€?

์ดํ•ญ๊ณ„์ˆ˜(Binomial Coefficient)๋Š” ์กฐํ•ฉ๋ก ์—์„œ ๋“ฑ์žฅํ•˜๋Š” ๊ฐœ๋…์œผ๋กœ ์ฃผ์–ด์ง„ ํฌ๊ธฐ ์ง‘ํ•ฉ์—์„œ ์›ํ•˜๋Š” ๊ฐœ์ˆ˜๋งŒํผ ์ˆœ์„œ์—†์ด ๋ฝ‘๋Š” ์กฐํ•ฉ์˜ ๊ฐ€์ง“์ˆ˜๋ฅผ ์ผ์ปซ๋Š”๋‹ค.
แ„‰แ…ณแ„แ…ณแ„…แ…ตแ†ซแ„‰แ…ฃแ†บ 2023-04-09 แ„‹แ…ฉแ„’แ…ฎ 8 18 14

์‰ฝ๊ฒŒ ์ƒ๊ฐํ•˜๋ฉด $_nC_r$์—์„œ n๋ถ€ํ„ฐ r๊ฐœ์˜ ์ˆ˜๊นŒ์ง€ 1๋งŒํผ ๊ฐ์†Œํ•˜๋ฉด์„œ ๊ณฑํ•œ ๊ฐ’์ด ๋ถ„์ž, r!๊ฐ€ ๋ถ„๋ชจ ๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ  ๊ณ„์‚ฐํ•˜๋ฉด ์‰ฝ๊ฒŒ ๊ณ„์‚ฐํ•  ์ˆ˜ ์žˆ๋‹ค.

ํƒœ๊ทธ: ,

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ:

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ