I am trying to use this method in order to break down bases with large exponents because data types in the standard C++ library do not store numbers that large.
The problem is in the last loop where I use the fmod() function to mod my large numbers. The answer is supposed to be 1 but I am getting 16. Does someone see a problem?
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
typedef vector<int> ivec;
ivec binStorage, expStorage;
void exponents()
{
for (int j=binStorage.size(); j>=0; j--)
if(binStorage[binStorage.size()-j-1]!=0)
expStorage.push_back(pow(2, j));
}
void binary(int number)
{
int remainder;
if(number <= 1)
{
cout << number;
return;
}
remainder = number%2;
binary(number >> 1);
cout << remainder;
binStorage.push_back(remainder);
}
int main()
{
int num = 117;
int message = 5;
int mod = 19;
int prod = 1;
binary(num);
cout << endl;
exponents();
cout << "\nExponents: " << endl;
for (int i=0; i<expStorage.size(); i++)
cout << expStorage[i] << " " ;
cout << endl;
cout << "\nMessage" << "-" << "Exponent" << endl;
for (int i=0; i<expStorage.size(); i++)
{
cout << message << "-" << expStorage[i] << endl;
prod *= fmod(pow(message, expStorage[i]), mod);
}
cout << "\nAnswer: " << fmod(prod, mod) << endl;
return 0;
}
Here are my results:
1110101
Exponents:
64 32 16 4 1
Message-Exponent
5-64
5-32
5-16
5-4
5-1
Answer: 16
Process returned 0 (0x0) execution time : 0.085 s
Press any key to continue.
Edit: Here is the problem loop.
for (int i=0; i<expStorage.size(); i++)
{
cout << message << "-" << expStorage[i] << endl;
prod *= fmod(pow(message, expStorage[i]), mod);
}
main, one or two constant input values, the problematic function call, and perhaps some output to demonstrate that the output isn't what it should be. This should have been your first debugging step. - Lightness Races in Orbit