0

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;

MicroVirus
  • 5,324
  • 2
  • 28
  • 53
Sick654
  • 79
  • 9
  • 8
    Are you trying to do exact calculations over the integers (e.g. for cryptography)? If so, you won't find a built-in C++ function for this, and you won't want any kind of floating point approximation. Try searching for "modular exponentiation" and you'll find some relatively simple methods to achieve what you want, without having to generate the enormous intermediate values. – Jim Lewis Jun 09 '16 at 20:14

2 Answers2

1

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;
}
eigenaar
  • 77
  • 1
  • 2
0

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);
}
malioboro
  • 3,097
  • 4
  • 35
  • 55
  • my c++ doesnt support long long, I use codeblocks, any idea how to fix that? – Sick654 Jun 09 '16 at 20:35
  • seriously? impossible, long long int is a built-in data type – malioboro Jun 09 '16 at 21:23
  • |11|error: ISO C++ 1998 does not support 'long long'| – Sick654 Jun 09 '16 at 21:35
  • I think it's compiler problem, try to update it or see this question : http://stackoverflow.com/questions/4017621/how-to-do-portable-64-bit-arithmetic-without-compiler-warnings. But if your number is not big enough you can just using int – malioboro Jun 09 '16 at 21:46
  • I try write code using codeblocks and it works well, my example try to calculate 300^31 mod 33 – malioboro Jun 09 '16 at 22:16
  • 1
    @Sick654 Updating the compiler is easy. Find a download link for mingw-w64, install it somewhere (don't touch any settings). Open CB settings and change compiler path to where you just placed mingw-w64. Also, while you're changing compiler settings, you should also enable `-std=c++14` flag, which will enable latest fancy C++ features. – HolyBlackCat Jun 09 '16 at 22:30