Binomial Coefficient | DP | Python code for the above approach ; Base case ; C ( n , r ) = C ( n , n - r ) Complexity for this code is lesser for lower n - r ; set smallest prime factor of each number as itself ; set smallest prime factor of all even numbers as 2 ; Check if i is prime ; All multiples of i are composite ( and divisible by i ) so add i to their prime factorization getpow ( j , i ) times ; dictionary to store power of each prime in C ( n , r ) ; For numerator count frequency of each prime factor ; Recursive division to find prime factorization of i ; For denominator subtract the power of each prime factor ; Recursive division to find prime factorization of i ;  ; Use ( a * b ) % mod = ( a % mod * b % mod ) % mod ; pow ( base , exp , mod ) is used to find ( base ^ exp ) % mod fast ; Driver code
import math NEW_LINE class GFG : NEW_LINE INDENT def nCr ( self , n , r ) : NEW_LINE INDENT if r > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n - r > r : NEW_LINE INDENT r = n - r NEW_LINE DEDENT SPF = [ i for i in range ( n + 1 ) ] NEW_LINE for i in range ( 4 , n + 1 , 2 ) : NEW_LINE INDENT SPF [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , n + 1 , 2 ) : NEW_LINE INDENT if i * i > n : NEW_LINE INDENT break NEW_LINE DEDENT if SPF [ i ] == i : NEW_LINE INDENT for j in range ( i * i , n + 1 , i ) : NEW_LINE INDENT if SPF [ j ] == j : NEW_LINE INDENT SPF [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT prime_pow = { } NEW_LINE for i in range ( r + 1 , n + 1 ) : NEW_LINE INDENT t = i NEW_LINE while t > 1 : NEW_LINE INDENT if not SPF [ t ] in prime_pow : NEW_LINE INDENT prime_pow [ SPF [ t ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prime_pow [ SPF [ t ] ] += 1 NEW_LINE DEDENT t //= SPF [ t ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n - r + 1 ) : NEW_LINE INDENT t = i NEW_LINE while t > 1 : NEW_LINE INDENT prime_pow [ SPF [ t ] ] -= 1 NEW_LINE t //= SPF [ t ] NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE for i in prime_pow : NEW_LINE INDENT ans = ( ans * pow ( i , prime_pow [ i ] , mod ) ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT n = 5 NEW_LINE k = 2 NEW_LINE ob = GFG ( ) NEW_LINE print ( " Value ▁ of ▁ C ( " + str ( n ) + " , ▁ " + str ( k ) + " ) ▁ is " , ob . nCr ( n , k ) ) NEW_LINE