How to calculate nPr mod m, when m is a prime number? - factorial

I need to find out the value of nPr%m.
This is the approach I used.
Find, n!%m, (n-r)!%m and divide them
However, for certain cases, (n-r)!%m is greater than n!%m, so the resultant nPr is 0.
What do I need to do then?

This is more a math question than a programming question, but anyway.
Note that
n! / (n - r)! = n * (n - 1) * ... * (n - r + 1)
Now for multiplication,
(a * b * c) % m = (((a * b) % m) * c) % m
i.e. rather than mod ming the entire product, you can mod m the intermediate result of any multiplication of two factors in the product.
I won't provide the full code here, but hopefully this will be enough for you to figure it out.

Related

How to efficiently verify whether pow(a, b) % b == a in C (without overflow)

I'd like to verify whether
pow(a, b) % b == a
is true in C, with 2 ≤ b ≤ 32768 (215) and 2 ≤ a ≤ b with a and b being integers.
However, directly computing pow(a, b) % b with b being a large number, this will quickly cause C to overflow. What would be a trick/efficient way of verifying whether this condition holds?
This question is based on finding a witness for Fermat's little theorem, which states that if this condition is false, b is not prime.
Also, I am also limited in the time it may take, it can't be too slow (near or over 2 seconds). The biggest Carmichael number, a number b that's not prime but also doesn't satisfy pow(a, b)% b == a with 2 <= a <= b (with b <= 32768) is 29341. Thus the method for checking pow(a, b) % b == a with 2 <= a <= 29341 shouldn't be too slow.
You can use the Exponentiation by squaring method.
The idea is the following:
Decompose b in binary form and decompose the product
Notice that we always use %b which is below 32768, so the result will always fit in a 32 bit number.
So the C code is:
/*
* this function computes (num ** pow) % mod
*/
int pow_mod(int num, int pow, int mod)
{
int res = 1
while (pow>0)
{
if (pow & 1)
{
res = (res*num) % mod;
}
pow /= 2;
num = (num*num)%mod;
}
return res;
}
You are doing modular arithmetic in Z/bZ.
Note that, in a quotient ring, the n-th power of the class of an element is the class of the n-th power of the element, so we have the following result:
(a^b) mod b = ((((a mod b) * a) mod b) * a) mod b [...] (b times)
So, you do not need a big integer library.
You can simply write a C program using the following algorithm (pseudo-code):
declare your variables a and b as integers.
use a temporary variable temp that is initialized with a.
do a loop with b steps, and compute (temp * a) mod b at each step, to get the new temp value.
compare the result with a.
With this formula, you can see that the highest value for temp is 32768, so you can choose an integer to store temp.

How to use Modulo efficiently?

Im doing a (for myself) very complex task, where i have to calculate the largest possible number of sequences when given a number n of segments.
I found out that the Catalan Number represents this sequences, and i got it to work for n<=32. The results i get should be calculated mod 1.000.000.007. The problem i have is that "q" and "p" get to big for a long long int and i can't just mod 1.000.000.007 before dividing "q" and "p" because i would get a different result.
My question is, is there a really efficient way to solve my problem, or do i have to think about storing the values differently?
My limitations are the following:
- stdio.h/iostream only
- only Integers
- n<=20.000.000
- n>=2
#include <stdio.h>
long long cat(long long l, long long m, long long n);
int main(){
long long n = 0;
long long val;
scanf("%lld", &n);
val = cat(1, 1, n / 2);
printf("%lld", (val));
return 0;
}
long long cat(long long q, long long p, long long n){
if (n == 0) {
return (q / p) % 1000000007;
}
else {
q *= 4 * n - 2;
}
p *= (n + 1);
return cat(q, p, n - 1);
}
To solve this efficiently, you'll want to use modular arithmetic, with modular inverses substituting for division.
It's simple to prove that, in the absence of overflow, (a * b) % c == ((a % c) * b) % c. If we were just multiplying, we could take results mod 1000000007 at every step and always stay within the bounds of a 64-bit integer. The problem is division. (a / b) % c does not necessarily equal ((a % c) / b) % c.
To solve the problem with division, we use modular inverses. For integers a and c with c prime and a % c != 0, we can always find an integer b such that a * b % c == 1. This means we can use multiplication as division. For any integer d divisible by a, (d * b) % c == (d / a) % c. This means that ((d % c) * b) % c == (d / a) % c, so we can reduce intermediate results mod c without screwing up our ability to divide.
The number we want to calculate is of the form (x1 * x2 * x3 * ...) / (y1 * y2 * y3 * ...) % 1000000007. We can instead compute x = x1 % 1000000007 * x2 % 1000000007 * x3 % 1000000007 ... and y = y1 % 1000000007 * y2 % 1000000007 * y3 % 1000000007 ..., then compute the modular inverse z of y using the extended Euclidean algorithm and return (x * z) % 1000000007.
If you're using gcc or clang and a 64-bit target, there exists a __int128 type. This gives you extra bits to work with, but obviously only to a point.
Most likely the easiest way to deal with this kind of issue is to use a "bignum" library, i.e. a library that deals with representing and doing arithmetic on arbitrarily large numbers. The arguably most popular open source example is libgmp - you should be able to get your algorithm going quite easily with that. It's also tuned to high performance standards.
Obviously you can reimplement this yourself, by representing your numbers as e.g. arrays of integers of a certain size. You'll have to implement algorithms for doing basic arithmetic such as +, -, *, /, % yourself. If you want to do this as a learning experience that's fine, but there's no shame in using libgmp if you just want to focus on the algorithm you're trying to implement.

Complex division using Fixed Point

I'm working on writing a C program to perform division of 2 complex numbers in Fixed Point.
I'm not able to get the fractional part from it. Below is more details on it.
I have 2 complex numbers:
N = a + ib
M = c + jd
I need to do N/M in fixed point (not using floating point)
Example values for the above complex numbers can be:
a = 1.55, b = 1.44, c = 1.24, d = 0.55
N = 1.55 + i(1.44)
M = 1.24 + j(0.55)
For converting to Fixed Point, I multiply these a, b, c and d with 2^14.
After that they become:
a = 0x6333, b = 0x5c28, c = 0x4f5c and d = 0x2333
Then to perform the N/M operation I do:
N/M = (a + ib)/(c + jd) = ((a + ib) * (c - jd)) / ((c + jd) * (c - jd))
Then for the real part alone:
(ac + bd) / (c^2 + d^2)
and so on..
The issue I'm facing is that I'm not understanding how to get the fractional part from the division.
I'm getting only the decimal part which is mostly either 1 or 0.
What is the correct way to get the fractional part? In the above example, the real part should be something like 1.47490. But I'm only able to get 1.
Can anyone please help me with the right way in doing the complex division for Fixed Point?
Thank you very much.
In fixed point division and multiplication one must notice that the result value must have also scaling factor K.
in addition / subtraction:
a * K + b * K = K * ( a + b)
in multiplication:
(a * K) * (b * K) = K^2 * (a * b) --> must compensate with 1/K
proper form: (aK * bK) / K
in division:
(a * K) / (b * K) = a / b --> must pre-multiply with K
proper form: (aK * K) / (bK)
For two complex X=a+jb, and Y=c+jd, where j=sqrt(-1), and a, b, c, d are real numbers, the division X/Y is given by
(ac+bd)/(c^2+d^2) + j(bc-ad)/(c^2+d^2)
Let K = 2^14, the binary digit for saving the fraction, as you mentioned.
Let A is the fixed number representation of a, i.e. A = a * K, and similarly let B = b*K, C=c*K, and lastly D=d*K. Assume your number is not big enough to overflow the integer of your computer, in the following calculations:
You should first calculate U = A * C + B * D, V = C * C + D * D, W = B * C - A * D
Then, you should calculate V' = V >> 14. Then, the real part of X/Y is U/V', and the imaginary part of X/Y is W/V', with both parts represented in your fixed point form.

Best way to compute ((2^n )-1)mod p

I'm working on a cryptographic exercise, and I'm trying to calculate (2n-1)mod p where p is a prime number
What would be the best approach to do this? I'm working with C so 2n-1 becomes too large to hold when n is large
I came across the equation (a*b)modp=(a(bmodp))modp, but I'm not sure this applies in this case, as 2n-1 may be prime (or I'm not sure how to factorise this)
Help much appreciated.
A couple tips to help you come up with a better way:
Don't use (a*b)modp=(a(bmodp))modp to compute 2n-1 mod p, use it to compute 2n mod p and then subtract afterward.
Fermat's little theorem can be useful here. That way, the exponent you actually have to deal with won't exceed p.
You mention in the comments that n and p are 9 or 10 digits, or something. If you restrict them to 32 bit (unsigned long) values, you can find 2^n mod p with a simple (binary) modular exponentiation:
unsigned long long u = 1, w = 2;
while (n != 0)
{
if ((n & 0x1) != 0)
u = (u * w) % p; /* (mul-rdx) */
if ((n >>= 1) != 0)
w = (w * w) % p; /* (sqr-rdx) */
}
r = (unsigned long) u;
And, since (2^n - 1) mod p = r - 1 mod p :
r = (r == 0) ? (p - 1) : (r - 1);
If 2^n mod p = 0 - which doesn't actually occur if p > 2 is prime - but we might as well consider the general case - then (2^n - 1) mod p = -1 mod p.
Since the 'common residue' or 'remainder' (mod p) is in [0, p - 1], we add a some multiple of p so that it is in this range.
Otherwise, the result of 2^n mod p was in [1, p - 1], and subtracting 1 will be in this range already. It's probably better expressed as:
if (r == 0)
r = p - 1; /* -1 mod p */
else
r = r - 1;
To take modulus you somehow must have 2^n-1 or you will move in a different direction of algorithms, interesting but seperate direction somehow, so i recommend you to use big int concept as it will be easy... make a structure and implement a big value in small values, e.g.
struct bigint{
int lowerbits;
int upperbits;
}
decomposition of the statement also has solution like 2^n = (2^n-4 * 2^4 )-1%p decompose and seperatly handle them, that will be quite algorithmic then
To compute 2^n - 1 mod p, you can use exponentiation by squaring after first removing any multiple of (p - 1) from n (since a^{p-1} = 1 mod p). In pseudo-code:
n = n % (p - 1)
result = 1
pow = 2
while n {
if n % 2 {
result = (result * pow) % p
}
pow = (pow * pow) % p
n /= 2
}
result = (result + p - 1) % p
I came across the answer that I am posting here, when solving one of the mathematical problems on HackerRank, and it has worked for all the given test cases given there.
If you restrict n and p to 64 bit (unsigned long) values, then here is the mathematical approach :
2^n - 1 can be written as 1*[ (2^n - 1)/(2 - 1) ]
If you look at this carefully, this is the sum of the GP 1 + 2 + 4 + .. + 2^(n-1)
And voila, we know that (a+b)%m = ( (a%m) + (b%m) )%m
If you have a confusion whether the above relation is true or not for addition, you can google for it or you can check this link : http://www.inf.ed.ac.uk/teaching/courses/dmmr/slides/13-14/Ch4.pdf
So, now we can apply the above mentioned relation to our GP, and you would have your answer!!
That is,
(2^n - 1)%p is equivalent to ( 1 + 2 + 4 + .. + 2^(n-1) )%p and now apply the given relation.
First, focus on 2n mod p because you can always subtract one at the end.
Consider the powers of two. This is a sequence of numbers produced by repeatedly multiplying by two.
Consider the modulo operation. If the number is written in base p, you're just grabbing the last digit. Higher digits can be thrown away.
So at some point(s) in the sequence, you get a two-digit number (a 1 in the p's place), and your task is really just to get rid of the first digit (subtract p) when that happens.
Stopping here conceptually, the brute-force approach would be something like this:
uint64_t exp2modp( uint64_t n, uint64_t p ) {
uint64_t ret = 1;
uint64_t limit = p / 2;
n %= p; // Apply Fermat's Little Theorem.
while ( n -- ) {
if ( ret >= limit ) {
ret *= 2;
ret -= p;
} else {
ret *= 2;
}
}
return ret;
}
Unfortunately, this still takes forever for large n and p, and I can't think of any better number theory offhand.
If you have a multiplication facility which can compute (p-1)^2 without overflow, then you can use an analogous algorithm using repeated squaring with a modulo after each square operation, and then take the product of the series of square residuals, again with a modulo after each multiplication.
step 1. x= shifting 1 n times and then subtract 1
step 2.result = logical and operation of x and p

What is wrong with my Catalan Number logic?

I wanted to write a code for Catalan Numbers.Catalan Numbers are defined as follows:
C(n) = 2n C n/(n+1). But instead of computing (2n C n) I wanted to calculate the catalan numbers bottom up using the following facts:
Catalan(n) =
2n! /n! * n! * (n+1)
Catalan(n+1) =
2*(n+1)
--------------------------- =
(n+1)! * (n+1)! * ((n+1)+1)
(2n+2) * (2n+1) * 2n!
------------------------------- =
(n+1) * n! * (n+1) * n! * (n+2)
(2n+2) * (2n+1) * 2n!
----------------------------------- =
(n+1) * (n+2) * n! * n! * (n+1)
(2n+2) * (2n+1)
--------------- * Catalan(n)
(n+1) * (n+2)
Now utilizing the above fact this is my following code:
int catalan(int n)
{
if (n == 1)
return 1 //since c(1)=1 is my base case
else
return (((2*n+2) * (2*n+1))/((n+1)*(n+2))) * catalan(n-1)
}
Now,my question is why does the above function return 12 when my input is 4 .It should return 14 because c(4)=14.
Can anyone help me, please?
Even though the original expression for C(n) might be wrong, the actual recurrence
is correct.
You can further simplify that to
But that gives you C(n+1) in terms of C(n). What you want is C(n) in terms of C(n-1). Plug in n-1 to get
Also note that in order to prevent the integer division from truncating your result, you need to multiply first and then divide.
int catalan(int n) {
if (n == 1)
return 1;
else
return 2 * (2*n - 1) * catalan(n-1) / (n+1);
}
EDIT: if the values of the need to be used frequently and not just calculated once, it's probably a good idea to use memoization, to avoid calculating them more than once.
Additionally, notice that due to the large growth rate, the Catalan numbers quickly overflow any of the predefined integer data types C has.
According to http://en.wikipedia.org/wiki/Catalan_number the recurrence formula is:
C(n+1)=2(2n+1)/(n+1) * C(n) or C(n)=2(2(n-1)+1)/n * C(n-1)
I think you have forgotten this transformation from C(n+1) to C(n).
There is an error in your formula. Your formula is for calculating c(n+1) yet your input is n. This can be fixed by decreasing the value of n by one before using it in the calculation:
int catalan(int n)
{
if (n == 1)
return 1 //since c(1)=1 is my base case
else
n=n-1
return (((2*n+2) * (2*n+1))/((n+1)*(n+2))) * catalan(n)
}
Edit: As pointed out by abeln, the code above will fail due to integer division dropping the remainder. Use the code below instead:
int catalan(int n)
{
if (n == 1)
return 1 //since c(1)=1 is my base case
else
n=n-1
return ((catalan(n) * (2*n+2) * (2*n+1))/((n+1)*(n+2)))
}
When you go from the mathematical expression to code, you are implicitly replacing n with n-1 in the Catalan() parts, but not in the expression itself. So you are computing the multiplier for value N and multiplying it by C(N-1). Try substituting N-1 for N in your equation, which leads to:
int catalan(int n)
{
if (n == 1)
return 1 //since c(1)=1 is my base case
else
return (((2*n) * (2*n-1))/((n)*(n+1))) * catalan(n-1)
}
In your formula, you have
(2n)!
C(n) = ----------------
(n+1)! * n! * n!
when in fact the Catalan Numbers are defined as
(2n)!
C(n) = ----------------
(n+1)! * n!
i.e. you have one factorial on the denominator too much

Resources