need to write 3 functions: 1)main 2)int mod_test(int a, int e, int n)
3)void mod_test(int a, int x, int b, int y, int n, int *out1, int *out2)*out1 here means output, so there are 2 outputs; these functions simply attempt to solve the issue of overflow; not sure how to implement 3) which declares 2 pointers as parameters: should I use nested while loops; just not sure!! Below is the code for 2):
1 2 3 4 5 6 7 8 9 10 11 12
int mod_test(int a, int e, int n) //a to the e mod n: a^e mod n
{
int i = 0;
int result = 1;
while(i < e)
{
result = result * (a % n);
i++;
}
return result;
}
Hi,
According to the algorithm a^e, what you are doing to calculate (result) is wrong.
You forgot to do mod operation before your function returns.
However, it is unclear what test your mod_test() func actually conducts just by looking at your quick description.
1 2 3 4 5 6 7 8 9 10 11
int mod_test(int a, int e, int n) // a to the e mod n: a^e mod n
{
int i = 1;
int result = a;
while(i < e)
{
result *= a;
i++;
}
return (result % n);
}
If the idea is to find a^e mod n without overflow affecting the results, the implementation of (2) should look something like this:
1 2 3 4 5 6 7 8 9
int mod_test(int a, int e, int n) //a to the e mod n: a^e mod n
{
int result = a;
for (int i=1; i<e; ++i)
result = (result * a) % n; // prevent overflow
return result;
}
Note that neither the code in the OP nor that by the poorly named person above is correct with regard to preventing overflow.
You didn't provide the requirements for the function (3) you were unsure how to write, and it isn't immediately obvious what it should do, so it's difficult to give you cogent advice.