I have a large number I want to take the remainder of. For example 300^31. When I try to use %
operator it says I cant use it on doubles, since it works only for integers. Is there any function for that calculation?
I tried to use a=pow(b,x)%d;
I have a large number I want to take the remainder of. For example 300^31. When I try to use %
operator it says I cant use it on doubles, since it works only for integers. Is there any function for that calculation?
I tried to use a=pow(b,x)%d;
If b
, x
and d
fit into integers, you can use
int expoModulo(int b, int x, int d) {
int a = 1;
for(int i=0; i<x; i++) {
a = (a*b)%d;
}
return a;
}
I think its better to take remainder while you trying to exponentiate. You can use Big Modulo Algorithm. It will help you avoid get big number. And after that you can just use long long instead of double.
I try to write this code in codeblocks 16.01 (codeblocks-16.01mingw-setup.exe) and it works pretty well (my code slightly different than the link code but it have the same concept):
#include<iostream>
using namespace std;
int bmod = 33;
int bigmod(long long int x,long long int b){ // x^b
int ans=1;
while(b){
if(b%2)ans=((long long)ans*x)%bmod;
b=b>>1;
x=((long long)x*x)%bmod;
}
return ans;}
int main(){
cout<<bigmod(300,31);
}