First of all I'm solving a programming problem rather than a math problem now.
The question is
Anish got an unbiased coin and he tossed it n times and he asked Gourabh to count all the number of possible outcomes with j heads, for all j from 0 to n. Since the number of possible outcome can be huge, he will tell the values modulo m. To be clear, we need to return one integer per value of j.
The question is simple, but the problem arises with the time limit, being 1.5 seconds, but with input n as large as 200000.
I used math.comb
to calculate the values, but it took more than 1.5 seconds to run.
So, are there any ways to calculate combinations in a faster way?
Edit#1:
Sample input:
2 998244353
Sample output:
1 2 1
Edit#2:
Here is the code that I've tried:
import math
n,m=input().split()
n = int(n)
m = int(m)
l = []
for i in range(n+1):
l.append(math.comb(n,i)%m)
print(*l)
P.S: Please let me know if this is off topic for this site and suggest a suitable SE site to post this question. Thanks in advance! This question is from an inter college contest which ended 2 months ago.
Here is the original problem: https://codeforces.com/gym/430360/problem/B (you'll need an account, and first time follow the "Contest Link" here to enter).
In case you are not able to view the problem, please find the picture below.
2**n
. So what you're looking for is an efficient way of calculatingsum(2**i % m for i in range(1, n+1))
. – Bendym
in the original question? Ifm
is a prime number, then this is definitely a question about using Lucas' theorem. Note that998244353
is, in fact, a prime number. – Valoracomb(n,k) == comb(n,n-k)
– Invagination/=
instead of//=
. Yeah, modular arithmetic optimizations are necessary. – Colorific