Here is the code to calculate nCr % P by using Fermat's little theorem
long long power(long long x, long long y, long long p)
{
long long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
// Returns n^(-1) mod p
long long modInverse(long long n, long long p)
{
return power(n, p-2, p);
}
// Returns nCr % p using Fermat's little
// theorem.
long long nCrModPFermat(long long n, long long r, long long p)
{
// Base case
if (r==0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long long fac[n+1];
fac[0] = 1;
for (long long i=1 ; i<=n; i++)
fac[i] = fac[i-1]*i%p;
return (fac[n]* modInverse(fac[r], p) % p *
modInverse(fac[n-r], p) % p) % p;
}
To optimise the code, I precalculated the fac[] array and passed it as an argument in the nCrModPFermat() function:
long long nCrModPFermat(long long n, long long r, long long p,long long fac[])
{
//same code as above
}
int main()
{
long long fac[2001];
fac[0] = 1;
for (long long i=1 ; i<=2000; i++) //calculating factorials upto 2000
fac[i] = fac[i-1]*i%M;
for(i=0;i<2000;i++)
nCrModPFermat(2000,i,M,fac);
}
My outputs where not as expected. Strangely, when I declared the fac[] array globally and calculated the factorials upto 2000 by calling a function:
long long fac[2001];
void funci()
{
fac[0] = 1;
for (long long i=1 ; i<=2000; i++) //calculating factorials upto 2000
fac[i] = fac[i-1]*i%M;
}
long long nCrModPFermat(long long n, long long r, long long p)
{
//same code as above
}
int main()
{
funci();
for(i=0;i<2000;i++)
nCrModPFermat(5000,i,M);
}
I got the expected outputs.
I just want to know why passing the array caused an error in the code
Related
I'm trying to write miller-rabin test. I found few codes such as:
https://www.sanfoundry.com/cpp-program-implement-miller-rabin-primality-test/
https://www.geeksforgeeks.org/primality-test-set-3-miller-rabin/
Of course all this codes works for 252097800623 ( which is prime number ), but this is becaouse they are parsing it to int. When I changed all ints to long long in this codes they are now returning NO. I also wrote my own code based on another article and it worked when I was testing it with small numbers like 11, 101, 17 and even 1000000007, but chrashed on greater numbers like 252097800623. I want to write program that works for all integers from 1 to 10^18
EDIT
here is modified code form 1st link:
/*
* C++ Program to Implement Milong longer Rabin Primality Test
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
/*
* calculates (a * b) % c taking long longo account that a * b might overflow
*/
long long mulmod(long long a, long long b, long long mod)
{
long long x = 0,y = a % mod;
while (b > 0)
{
if (b % 2 == 1)
{
x = (x + y) % mod;
}
y = (y * 2) % mod;
b /= 2;
}
return x % mod;
}
/*
* modular exponentiation
*/
long long modulo(long long base, long long exponent, long long mod)
{
long long x = 1;
long long y = base;
while (exponent > 0)
{
if (exponent % 2 == 1)
x = (x * y) % mod;
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}
/*
* Milong longer-Rabin primality test, iteration signifies the accuracy
*/
bool Miller(long long p,long long iteration)
{
if (p < 2)
{
return false;
}
if (p != 2 && p % 2==0)
{
return false;
}
long long s = p - 1;
while (s % 2 == 0)
{
s /= 2;
}
for (long long i = 0; i < iteration; i++)
{
long long a = rand() % (p - 1) + 1, temp = s;
long long mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1)
{
mod = mulmod(mod, mod, p);
temp *= 2;
}
if (mod != p - 1 && temp % 2 == 0)
{
return false;
}
}
return true;
}
//Main
int main()
{
long long iteration = 5;
long long num;
cout<<"Enter long longeger to test primality: ";
cin>>num;
if (Miller(num, iteration))
cout<<num<<" is prime"<<endl;
else
cout<<num<<" is not prime"<<endl;
return 0;
}
The code in the first link, which you replicated in your question, replacing the (bad) macro ll with long long (although this produces exactly the same preprocessed code) and all int with long long, is already broken for large values, see compiler explorer here. I forced the compiler to evaluate the Miller function for 252097800623 at compile time, replacing the call to rand() with one random number 123456.
As you can see the compiler is telling me that it cannot do so, because there are integer overflows in the program. In particular:
<source>:133:17: error: static_assert expression is not an integral constant expression
static_assert(Miller(num, iteration));
^~~~~~~~~~~~~~~~~~~~~~
<source>:62:12: note: value 232307310937188460801 is outside the range of representable values of type 'long long'
y = (y * y) % mod;
^
<source>:104:14: note: in call to 'modulo(123457, 63024450155, 252097800623)'
ll mod = modulo(a, temp, p);
^
<source>:133:17: note: in call to 'Miller(252097800623, 5)'
static_assert(Miller(num, iteration));
As you can see long long is simply too small to handle inputs that large to this algorithm.
You have N different balls numbered from 1 to N, and M different boxes numbered from 1 to M.
Input:
First line of input contains the number of test cases T. After that, next T lines contain the value of N and M.
Output:
For each test case, print the answer. As it can be very large, you should print it modulo 10^9 + 7.
I tried the below code, but it gives an error:
#include<iostream>
#include<cmath>
#include<math.h>
using namespace std;
int main()
{
unsigned short int T;
unsigned long int N,M;
cin>>T;
for (int i = 0; i < T; i++)
{
cin>>N>>M;
long int res;
res= pow(M,N);
int c=0;
c=pow(10,9);
res=res%(c + 7);
cout<<res<<endl;
}
return 0;
}
You must be facing integer overflow problem, that's why you must have been getting wrong answer.
Do the following steps to fix this problem.
change the unsigned long to long long or unsigned long long. (Why? Think).
Use the logarithmic user-defined function to calculate the value of the res = pow(M,N) along with the modulo consideration side-by-side. This will boost up your program.
See my code snippet to check what changes to be made:
#include<iostream>
#define MOD 1000000007
int main() {
unsigned short int T;
unsigned long long N , M , result;
unsigned long long power(unsigned long long, unsigned long long); /*prototype of power*/
std::cin>>T;
for (int i = 0; i < T; i++) {
std::cin >> N >> M;
result = power(M , N);
std::cout << result << std::endl;
}
return 0;
}
unsigned long long power(unsigned long long M, unsigned long long N) {
if(N == 0) {
return 1;
}
unsigned long long result = power(M , N/2);
result = (result * result) % MOD;
if(N%2 == 1) {
result = (result * M) % MOD;
}
return result;
}
I have to generate the n-th fibonacci number from the first (zero-th) number being a and second being b. Below is my code for calculating this. I have been using matrix exponentiation method:
But the solution is wrong.
costum input:509618737 460201239 229176339(in order a,b,n)a=zeroth value,b=first value,n=Nth value to be found.
output:995159166
correct output:945141656
What is the problem with my code?
#include<iostream>
using namespace std;
void multiply(long long F[2][2], long long M[2][2]);//prototype of function multiplying 2 matrices.
void power(long long F[2][2],long long n);//prototype for incresing power
long long fib(long long n,long long a,long long b)//function that returns result as answer modulo 10^9+7(since answer is too long).
{
long long F[2][2] = {{1,1},{1,0}};
if (n == 0)
return a;
else if(n==1)
return b;
else if(n>1)
power(F, n-1);
return (F[0][0]*a+F[0][1]*b)%1000000007;//here's where i am confused ,whether i should multyply a first or b first i.e.f[0][0]*a+f[0][1]*b or f[0][0]*b+f[0][1]*a.plz explain this point too.
}
void power(long long F[2][2], long long n)
{
if( n == 0 || n == 1)
return;
long long M[2][2] = {{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
}
void multiply(long long F[2][2], long long M[2][2])//matrices multiplied.
{
long long x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
long long y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
long long z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
long long w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
int main()
{
long long t, a, b, n, ans;
cin>>t;//# of test cases
while(t--)
{
cin>>a;//zeroth value
cin>>b;//first value
cin>>n;//Nth fibonaaci no. to be generated
ans=fib(n,a,b);//value of Nth no.
cout<<ans<<"\n";
}
return 0;
}
How can we store and print factorial(2^n) / (2^n -1))mod1000000009 in C++.Here n can be as large as 20. When I try to print this using the following code, it shows segmentation fault for n=20
#include
#include
using namespace std;
long int factorial(int n)
{
if(n<=1){return 1;}
else
return (n%1000000009)*(factorial(n-1))%1000000009;
}
int main()
{
int K;
long long int numofmatches=0;
long long int denominator=0;
long long int factor=0;
long long int times=0;
long long int players=0;
cin>>K;
if(K==1)
{
cout<<2<<endl<<2<<endl;
return 0;
}
else
{
denominator=pow(2,K);
cout<<"Denominator="<<denominator<<endl;
numofmatches=factorial(denominator)%1000000009;
denominator-=1;
cout<<"numberofmatches="<<numofmatches<<endl;
cout<<"Denominator="<<denominator<<endl;
factor=numofmatches/denominator;
cout<<"Factor="<<factor<<endl;
while(times<=denominator)
{
cout<<(times*factor)<<endl;
++times;
}
}
return 0;
}
First of all, note that (2^n)! / (2^n-1) is equal to (2^n-2)! x 2^n.
Now, (2^20-2)! by itself is already an extremely large number to calculate.
What you can do instead, is to modulo the intermediate result with 1000000009 after every multiplication:
#define MAX ((1<<20)-2)
unsigned long long res = 1;
for (unsigned int i=1; i<=MAX; i++)
res = (res*i)%1000000009;
res = (res*(MAX+2))%1000000009;
If you want to iterate all values of n between 1 and 20, then you can use:
#define MAX_N 20
unsigned int arr[MAX_N+1] = {0};
void Func()
{
unsigned int i = 1;
unsigned long long res = 1;
for (int n=1; n<=MAX_N; n++)
{
unsigned int max = (1<<n)-2;
for (; i<=max; i++)
res = (res*i)%1000000009;
arr[n] = (unsigned int)((res*(max+2))%1000000009);
}
}
BTW, for any n larger than 29 the result will simply be 0, as (2^30-2) is larger than 1000000009.
So (2^30-2)! is divisible by 1000000009, and therefore, (2^30-2)! mod 1000000009 equals 0.
I was doing this problem called arithmetic progression on Hackerrank.
https://www.hackerrank.com/challenges/arithmetic-progressions
My solution passed all first six tests. I have tried every possible way of optimizing my code, including caching, more efficient operation. I still could not pass the test. The two places I think I failed is factorial function and pow function.
Basically, I used unordered_map to store all of the previous results. If the argument is one of the key, I will just returned the result right away.
Here is my code:
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <ctime>
#include <sys/time.h>
using namespace std;
#define mod(m) (m > 1000003) ? m % 1000003 : m
//used for hashing the pair
namespace std {
template<typename a, typename b>
struct hash< pair<a, b> > {
private:
const hash<a> ah;
const hash<b> bh;
public:
hash() : ah(), bh() {};
size_t operator()(const std::pair<a, b> &p) const {
return ah(p.first) ^ bh(p.second);
}
};
} // namespaces
//the code below is used for collecting statistics
/*
typedef unsigned long long timestamp_t;
static timestamp_t get_timestamp ()
{
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}
*/
//note that the number could get really large, that's why I use unsigned long long for most of data type
static unsigned long long cache_D[100000];
static unsigned long long cache_d[100000];
static unsigned long long cache_p[100000];
static unordered_map<unsigned long long, unsigned long long> cache_F; //use unordered_map to store the factorial, avg insert, lookup O(1)
static unordered_map<pair<unsigned long long, unsigned long long>, unsigned long long> cache_P; //use unordered_map to store the pow
//static double pow_sec = 0;
//static double fac_sec = 0;
/**
* Use the fast pow algorithm. On top of that, I add caching (stored in unordered map) to speed up the pow
* #param x base
* #param y exponent
* #return x ^ y
*/
unsigned long long pow(unsigned long long x, unsigned long long y)
{
//timestamp_t t0 = get_timestamp();
pair<unsigned long long, unsigned long long> curr(x, y);
if(cache_P.find(curr) != cache_P.end())
{
//timestamp_t t1 = get_timestamp();
//pow_sec += (t1 - t0) / 1000000.0L;
return cache_P[curr];
}
unsigned long long result = 1;
unsigned long long mod_x = mod(x);
//unsigned long long count = 0;
while( y )
{
if ( y & 1 )
{
unsigned long long temp = result * mod_x;
result = mod(temp);
}
y >>= 1;
unsigned long long temp = mod_x * mod_x;
mod_x = mod(temp);
}
cache_P[curr] = result;
//timestamp_t t1 = get_timestamp();
//pow_sec += (t1 - t0) / 1000000.0L;
return result;
}
/**
* same idea as pow, caching whenever I can
* #param x number to be factorialized
* #return x!
*/
unsigned long long factorial(unsigned long long x)
{
//timestamp_t t0 = get_timestamp();
if (cache_F.find(x) != cache_F.end())
{
//timestamp_t t1 = get_timestamp();
//fac_sec += (t1 - t0) / 1000000.0L;
return cache_F[x];
}
else
{
unsigned long long result = 1;
//here we go from x to 1 since we could speed up operation as soon as we have x - 1 or x - 2 or x - 3 in our caching (just x * (x - 1)! )
for(unsigned long long i = x; i >= 1; i--)
{
if(cache_F.find(i) != cache_F.end())
{
unsigned long long temp1 = result * cache_F[i];
result = mod(temp1);
cache_F[x] = result;
//timestamp_t t1 = get_timestamp();
//fac_sec += (t1 - t0) / 1000000.0L;
return result;
}
unsigned long long mod_i = mod(i);
unsigned long long temp2 = result * mod_i;
result = mod(temp2);
}
cache_F[x] = result;
//timestamp_t t1 = get_timestamp();
//fac_sec += (t1 - t0) / 1000000.0L;
return result;
}
}
void query(int from, int to)
{
unsigned long long k = 0;
unsigned long long constant = 1;
for(int i = from - 1; i < to; i++)
{
k += cache_p[i];
unsigned long long temp = constant * cache_D[i];
constant = mod(temp);
}
unsigned long long temp = constant * factorial(k);
constant = mod(temp);
printf("%llu %llu\n", k, constant);
}
void update(int from, int to, int how_much)
{
for(int i = from - 1; i < to; i++)
{
cache_p[i] += how_much;
unsigned long long temp = cache_D[i] * pow(cache_d[i], (unsigned long long)how_much);
cache_D[i] = mod(temp);
}
}
int main() {
int num_vec, num_operations;
FILE *pFile = fopen("input.txt", "r");
fscanf(pFile, "%d", &num_vec);
for(int i = 0; i < num_vec; i++)
{
unsigned long long a, d, q;
fscanf(pFile, "%llu %llu %llu", &a, &d, &q);
cache_d[i] = d;
cache_p[i] = q;
cache_D[i] = pow(d, q);
}
fscanf(pFile, "%d", &num_operations);
for(int i = 0; i < num_operations; i++)
{
int what_operation, from, to;
fscanf(pFile, "%d %d %d", &what_operation, &from, &to);
if(what_operation == 0)
{
query(from, to);
}
else if (what_operation == 1)
{
int add_q;
fscanf(pFile, "%d", &add_q);
update(from, to, add_q);
}
}
printf("sec for pow: %f\n sec for fac: %f", pow_sec, fac_sec);
return 0;
}
It would be really helpful if anyone knows how to further optimize my code. Thanks!
Regarding Factorial.
"unsigned long long" has a range from 0 to
18,446,744,073,709,551,615
the factorial of 21 is:
51,090,942,171,709,440,000
So, this means your function can only return the correct results for factorial of 0 through 20.
It will be a lot easier to start with a pre-built cache with 21 elements (zero through 20).
unsigned long long fact_cache [21] = {
1 ,
1 ,
2 ,
6 ,
24 ,
120 ,
720 ,
5040 ,
40320 ,
362880 ,
3628800 ,
39916800 ,
479001600 ,
6227020800 ,
87178291200 ,
1307674368000 ,
20922789888000 ,
355687428096000 ,
6402373705728000 ,
121645100408832000 ,
2432902008176640000
};
Now your factorial function can just look up the right value in the array (checking bounds if you like).
edit: (Realized the OP intended 'factorial mod 1000003")
I started by reading the answers to:
Fast way to calculate n! mod m where m is prime?
Based on the second answer, with code examples in python, and more information here:
http://www.algorithmist.com/index.php/Modular_inverse
He gave this Python code, as well as a possible improvement.
def factorialMod(n, modulus):
ans=1
if n <= modulus//2:
#calculate the factorial normally (right argument of range() is exclusive)
for i in range(1,n+1):
ans = (ans * i) % modulus
else:
#Fancypants method for large n
for i in range(n+1,modulus):
ans = (ans * i) % modulus
ans = modinv(ans, modulus)
ans = -1*ans + modulus
return ans % modulus
This has some advantages, over the original method when n is larger than the modulus divided by 2, since we can reduce the number of multiplications by solving for the modular inverse.
Because we know the modulus (1000003), we can solve for the modinv by using its totient (1000002).
In pseudo-code we get something like:
long factorial_mod( long n ) {
if( n > 1000003 )
return 0; //from Thomas's comment
if( cache[n] != 0 ) //if the cache has the answer
return cache[n];
long result = 1;
if ( n <= 500001 )
{
for( long i = 1; i <= n; i++ )
{
result = (result * i) % 1000003;
cache[i] = result;
}
}
else
{
for( long i = n+1; i <= 1000003; i++)
{
result = (result * i) % 1000003;
}
result = modinv(result, 1000003);
result = -1*result + 1000003;
}
result = result % 1000003;
cache[n] = result;
return result;
}
long modinv( long a, int modulus ) {
return modPow( a, 1000002, modulus); // ( (a to the totient) mod the modulus )
}
If we didn't want to compute the totient, we could have used extended euler GCD to solve for the modular inverse. (of course the totient of primes is very easy to compute...just subtract one).