NCk mod p in Ruby

Introduction

When I was solving AtCoder's past questions (ABC145 --D), I had a hard time finding nCk mod p. Therefore, How to find the binomial coefficient (nCk mod. P) and inverse element (a ^ -1 mod. P) that are often done I'm going to leave the easy-to-use ModCombination class here, which is a rewrite of.

code

class ModCombination
    def initialize(max)
        @MOD = 10 ** 9 + 7
        @fact = [1, 1]
        @factinv = [1, 1]
        @inv = [0, 1]
        2.upto(max) do |i|
            @fact << @fact[i-1] * i % @MOD
            @inv << @MOD - @inv[@MOD % i] * (@MOD / i) % @MOD
            @factinv << @factinv[i-1] * @inv[i] % @MOD
        end
    end
    def com(n, k)
        return 0 if n < k
        return 0 if n < 0 || k < 0
        return @fact[n] * (@factinv[k] * @factinv[n-k] % @MOD) % @MOD
    end
end

How to use

--Rewrite the value of @MOD if MOD is other than $ 10 ^ 9 + 7 $ --com (n, k) gives nCk% MOD

max = 10 ** 6
comb = ModCombination.new(max)
puts comb.com(n, k) # nCk mod 10 ** 9 + 7

in conclusion

I'll omit it because I think it will come out if I check what the above code is doing. I hope this article leads to someone's AC.

Recommended Posts

NCk mod p in Ruby
Class in Ruby
About eval in Ruby
Output triangle in Ruby
Variable type in ruby
Fast popcount in Ruby
ABC177 --solving E in Ruby
Validate JWT token in Ruby
Implemented XPath 1.0 parser in Ruby
Write class inheritance in Ruby
Update Ruby in Unicorn environment
Integer unified into Integer in Ruby 2.4
[Ruby] Exception handling in functions
Use ruby variables in javascript.
Multiplication in a Ruby array
About regular expressions in Ruby
Birthday attack calculation in Ruby
Judgment of fractions in Ruby
Find Roman numerals in Ruby
Try using gRPC in Ruby
[Ruby] Find numbers in arrays
Chinese Remainder Theorem in Ruby
Sorting hashes in a Ruby array
Basics of sending Gmail in Ruby
How to iterate infinitely in Ruby
Try to implement Yubaba in Ruby
Implementation of ls command in Ruby
Achieve 3-digit delimited display in Ruby
Encoding when getting in Windows + Ruby
Run GraphQL Ruby resolver in parallel
[Ruby] Extracting double hash in array
[Ruby] then keyword and case in
How to install Bootstrap in Ruby
String output method memo in Ruby
Implement a gRPC client in Ruby
Write keys and values in Ruby
[Super Introduction] About Symbols in Ruby
Hanachan in Ruby (non-destructive array manipulation)
Manipulating data in GCS during Ruby
Is there no type in Ruby?
Try file locking in Ruby directory
[Ruby] undefined method `dark?'occurs in rqr_code
openssl version information in ruby OPENSSL_VERSION
Ruby methods often used in Rails
Make Ruby segfault in two lines