Here is the PowerMod function I implemented using ttmath BigInt library:
#include <iostream>
#include <ttmath/ttmath.h>
using namespace std;
template <typename Integer>
Integer iPowerMod(Integer & n,Integer & p,Integer & b)
{
if (n>b) {n.Div(b,n);}
Integer iOut="1";
Integer iOutk=n;
Integer pref="1";
Integer ptemp=p;
Integer factor="2";
while (ptemp!=0)
{
while ((factor*pref)<=ptemp)
{
iOutk.Mul(iOutk);
if (iOutk>b) {iOutk.Div(b,iOutk);}
pref.Mul(2);
}
iOut.Mul(iOutk);
if (iOut>b) {iOut.Div(b,iOut);}
iOutk=n;
ptemp-=pref;
pref="1";
}
return iOut;
}
int main()
{
ttmath::UInt<100> n,p,b;
n="52526321452369856214521";
p="731779601467";
b="40420472400259202128651";
cout << iPowerMod(n,p,b);
return 0;
}
This is working for small (4-5 digits) integers, but not for large ones. As I am trying to build an encryption app using the RSA algorithm, I need it to work with large integers. I am using Mathematica 10.2 Kernel for verification. But, I've been unable to find the flaw. It'd be great if anyone could help. :)