Math Day is being celebrated at Coding Blocks. So Prateek Bhaiya rolled out a contest on Maths Problems. Here goes one.
Given three positive integers A,N,P. Compute AN! %P.
how to solve this q?
Math day hint for comptetive coding q
hello @sunneykumar309
use modular exponentiation to calcuate A^ N! %p
i.e
A^N! % P =((( (A^N % p ) ^ N-1)%p)^N-2) β¦^1
by using property -> A^ (a*b) = (A^a)^b
use modular exponentation to compute each A^N %P and then print ur answer
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX 100000
int power(ll x, ll y)
{
int temp;
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temptemp;
else
return xtemptemp;
}
int main()
{
ll t;
cin>> t;
while(tβ)
{
ll a,n,p;
cin>> a>> n>> p;
ll ans=1,save=0;
//ll save=power(ans,n);
for(int i=1;i<=n;i++)
{
save=power(a,i);
cout<<save<<endl;
ans=(save%p);
cout<<ans<<endl;
}
ll real=ans%p;
cout<<real<<endl;
}
}
i am getting WA in various question
*test casesβ¦
@sunneykumar309
check now->
a) use long long everywhere to avoid overflow
b) use mod property (a * b)%mod=(a%mod * b %mod)%mod;
thankx bhai β¦
still the error is same i am getting WA in 4/5 test cases.
ok question name is MATH DAY
check ur power function, there u need to apply modulo as well to avoid overflow.
read about modular exponentiation for more details
chekc now->
also check my very first response , i corrected the formula.
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX 100000
/ll power(ll x, ll y) //changed int to ll
{
ll temp; //changed int to ll
if( y == 0)
return 1;
temp = power(x, y/2);
if (y%2 == 0)
return temptemp;
else
return xtemptemp;
} */
int power(int x, unsigned int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
if (x == 0) return 0; // In case x is divisible by 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;
}
int main()
{
ll t;
cin>> t;
while(tβ)
{
ll a,n,p;
cin>> a>> n>> p;
ll ans=a;
for(ll i=2;i<=n;i++)
{
ans=power(ans,i,p);
}
cout<<ans<<endl;
}
}
still i am getting wrong answer
pls check my last response, have already shared ur updated code.
- use long long everywhere
ok i got. it
β¦
i have one more doubtin evaluating function
https://online.codingblocks.com/app/player/151917/content/169698/5109/code-challenge
in this q