Curious behaviour of inverse modulo - c++

I wrote the following code to calculate n!modulo p...Given that n and p are close...but its running in a rather funny way, cant figure out the bug..There is some overflow somewhere..The constraints are 1 < P <= 2*10^9
1 <= N <= 2*10^9
though it runs fine for few cases...what could be the error.I have used
(a/b)mod p = ((a mod p)*(b^(p-2))mod p)mod p
as p is prime....and wilsons theorem that (p-1)! mod p = p-1
#include<bits/stdc++.h>
#define _ ios_base::sync_with_stdio(0);cin.tie(0);
using namespace std;
unsigned int pow(unsigned int a, unsigned n,unsigned int p) {
unsigned int ret = 1;
while(n) {
if((n&1)== 1) ret=(ret*a)%p;
a=a%p;
a=(a*a)%p;
n=n>>1;
}
return ret;
}
int main(){_
int t;
cin>>t;
while(t--){
unsigned int n,p;
long long int r;
cin>>n>>p;
r=p-1;
if(n>=p){
cout<<"0\n";
}
else{
for(unsigned int i=p-1;i>n;i--){
r=((long long)r*pow(i,p-2,p))%p;
}
cout<<r<<"\n";
}
}
return 0;
}

21! is 51090942171709440000, while 2^64 is only 1844674407370955161: so if unsigned long long is a 64-bit quantity (as is likely), it doesn't fit.

Related

Bug in the following program could not be fixed C++

It might not be like other asked questions in stackoverflow. In this problem, it works fine, but in one case, it returns wrong answer. I'm trying to solve the logical issue of this program.
I wrote a program to calculate the sum of this:
x, n, a would be entered by the user:
Here is my program:
#include <iostream>
long long int unsigned fact (long long unsigned int a);
long long int unsigned comb (long long unsigned int n, long long unsigned int r);
long long unsigned intpower (long long unsigned int a, long long unsigned int n);
using namespace std;
int main()
{
int n;
long long unsigned int x, a;
cin >> a >> x >> n;
long long unsigned int sum = 0;
for (int i = 0; i <= n; i++) {
sum += comb(n, i)*intpower(x, i)*intpower(a, (n-i));
}
cout << sum;
return 0;
}
// Calculates Factorial
long long int unsigned fact (long long unsigned int a) {
long long int unsigned p = 1;
for (long long unsigned int i = 1; i <= a; i++) {
p *= i;
}
return p;
}
// Calculates the combination
long long int unsigned comb (long long unsigned int n, long long unsigned int r) {
return (fact(n)/fact(r)/fact(n-r));
}
long long unsigned intpower (long long unsigned int a, long long unsigned int n){
long long unsigned int p = 1;
for (long long unsigned int i = 1; i <=n ; i++){
p *= a;
}
return p;
}
But in one case, my program returns wrong answer. Here's the test done my a website that verifies the written programs for problems:
Do you guys have any idea why I got wrong answer in one test? The thing is I don't know what numbers would be entered in test 1, but there should be a logical issue that it gives wrong answer in one case.
Kind regards.
As the comments have pointed, the failing test case is most probably because of a corner-side with the maximum values of the inputs. The range that you can store in a long long int data type (if your compiler support the type) is from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807. It means that if in your case you have x, a and n as their maximum values, you will have an overflow. For an example, the output of your code with the following inputs is the same:
for:
int n = 10;
long long unsigned int x = 9999999999;
long long unsigned int a = 1000000000;
output is: 9223372036854775808
int n = 10;
long long unsigned int x = 1000000000;
long long unsigned int a = 1000000000;
the output is again: 9223372036854775808

C++ combination function always resulting 0

can anybody tell me why my Combination function is always resulting 0 ?
I also tried to make it calculate the combination without the use of the permutation function but the factorial and still the result is 0;
#include <iostream>
#include <cmath>
using namespace std;
int factorial(int& n)
{
if (n <= 1)
{
return 1;
}
else
{
n = n-1;
return (n+1) * factorial(n);
}
}
int permutation(int& a, int& b)
{
int x = a-b;
return factorial(a) / factorial(x);
}
int Combination(int& a, int& b)
{
return permutation(a,b) / factorial(b);
}
int main()
{
int f, s;
cin >> f >> s;
cout << permutation(f,s) << endl;
cout << Combination(f,s);
return 0;
}
Your immediate problem is that that you pass a modifiable reference to your function. This means that you have Undefined Behaviour here:
return (n+1) * factorial(n);
// ^^^ ^^^
because factorial(n) modifies n, and is indeterminately sequenced with (n+1). A similar problem exists in Combination(), where b is modified twice in the same expression:
return permutation(a,b) / factorial(b);
// ^^^ ^^^
You will get correct results if you pass n, a and b by value, like this:
int factorial(int n)
Now, factorial() gets its own copy of n, and doesn't affect the n+1 you're multiplying it with.
While we're here, I should point out some other flaws in the code.
Avoid using namespace std; - it has traps for the unwary (and even for the wary!).
You can write factorial() without modifying n once you pass by value (rather than by reference):
int factorial(const int n)
{
if (n <= 1) {
return 1;
} else {
return n * factorial(n-1);
}
}
Consider using iterative code to compute factorial.
We should probably be using unsigned int, since the operations are meaningless for negative numbers. You might consider unsigned long or unsigned long long for greater range.
Computing one factorial and dividing by another is not only inefficient, it also risks unnecessary overflow (when a is as low as 13, with 32-bit int). Instead, we can multiply just down to the other number:
unsigned int permutation(const unsigned int a, const unsigned int b)
{
if (a < b) return 0;
unsigned int permutations = 1;
for (unsigned int i = a; i > a-b; --i) {
permutations *= i;
}
return permutations;
}
This works with much higher a, when b is small.
We didn't need the <cmath> header for anything.
Suggested fixed code:
unsigned int factorial(const unsigned int n)
{
unsigned int result = 1;
for (unsigned int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
unsigned int permutation(const unsigned int a, const unsigned int b)
{
if (a < b) return 0;
unsigned int result = 1;
for (unsigned int i = a; i > a-b; --i) {
result *= i;
}
return result;
}
unsigned int combination(const unsigned int a, const unsigned int b)
{
// C(a, b) == C(a, a - b), but it's faster to compute with small b
if (b > a - b) {
return combination(a, a - b);
}
return permutation(a,b) / factorial(b);
}
You dont calculate with the pointer value you calculate withe the pointer address.

How to find modular multiplicative inverse in c++

#include <bits/stdc++.h>
#define mx 1000005
#define mod 1000003
using namespace std;
long long arr[mx];
int fact()
{
arr[0]=1;
for(int i=1; i<mx; i++)
{
arr[i]=((i%mod)*(arr[i-1]%mod))%mod;
}
}
int main()
{
int t;
long long a,b,C,E;
fact();
cin>>t;
while(t--)
{
cin>>a>>b;
C=(arr[a]%mod)%mod;
E=((arr[b])%mod)*((arr[a-b])%mod)%mod;
}
}
In this problem i have to calculate (C/E)%1000003. How could i do this using modular multiplicative inverse technique ? Is there other way to calculate this ?
Since 1000003 is prime.
long long mod = 1000003;
inline long long mpow(long long b, long long ex){
if (b==1)return 1;
long long r = 1;
while (ex ){
if (ex&1)r=(r * b)%mod;
ex = ex >> 1;
b = (b * b)%mod;}
return r;
}
Then do
inverse of E % mod is = mpow(E,mod-2)
Fermats's little theorem
geekforgeeks

Find the number of ways the N balls could be placed in the M boxes

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;
}

Printing (Factorial of 2^n)/(2^n -1)mod m in C++

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.