Reputation: 45
I created a modular calculator meant to go through a series of math executions and at the end take the mod of everything before. However, I keep on getting the wrong result.
#include <iostream>
using namespace std;
int main(){
int num1, num2, ans = 0;
char oper = ' ';
cin >> num1>> oper >> num2;
//The first time
if (oper == '*')
ans =num1*num2;
else if (oper == '+')
ans = num1+num2;
//other times
do {
cin>> oper >> num2;
if (oper == '*')
ans =ans*num2;
else if (oper == '+')
ans = ans+num2;
} while (oper!='%');
if (oper == '%')
ans = (ans % num2);
cout<<ans;
}
Input:
4
* 8805
* 99
* 12
+ 6
+ 367
* 575
+ 66
+ 9
* 8
* 8
* 711
+ 130
* 5
+ 5
+ 1
+ 73
* 811
* 33
+ 56
+ 80
* 350
* 116
+ 179
* 383
* 12
+ 59
+ 5150
* 10
+ 5
+ 8783
* 48
* 84
* 7
+ 390
+ 7057
* 10
+ 8366
+ 8856
* 99
* 9
+ 3019
+ 228
* 334
+ 75
+ 6353
+ 7151
* 8
% 1408
Output: -1240
Expected: 808
Any explanations? (BigInt
or double
or unsigned int
instead of int
don't seem to fix anything; I already tried all of those).
Upvotes: 0
Views: 89
Reputation: 2944
You got wrong answer because of int overflow.
Lets give you an example
Lets say your input like below
4
* 432
* 422
* 432
% 8
your program will give wrong answer because
after first input, ans = 4 * 432 = 1728
after second input, ans = 1732 * 432 = 746496 (which is greater than int highest range, it occurs int overflow and gives you wrong answer)
For this reason, we can use below modular arithmetic formula so that we can leave int overflow.
For Your Information, (26+3*2)%3 = (26%3 + 3%3 * 2%3) % 3
Try this
#include <iostream>
#define MAX 100 // guess at most 100 lines input
using namespace std;
int main()
{
int num1, count = 0, num2[MAX];
char oper[MAX];
cin >> num1;
do{
cin >> oper[count] >> num2[count];
count = count + 1;
}while(oper[count -1 ] != '%');
int ans = num1, remainder = num2[count - 1]; // last number is remainder value
for(int i = 0; i < count - 1; i++)
{
if(oper[i] == '+')
ans = (ans % remainder + num2[i] % remainder) % remainder;
if(oper[i] == '*')
ans = (ans % remainder * num2[i] % remainder) % remainder;
}
cout << ans << endl;
}
Upvotes: 2