-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathY_The_last_2_digits.cpp
67 lines (45 loc) · 1.17 KB
/
Y_The_last_2_digits.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <iomanip>
/*
First Solution -
int main()
{
long long a, b, c, d, multiply, lastTwoDigit;
std::cin >> a >> b >> c >> d;
multiply = a * b * c * d;
lastTwoDigit = multiply % 100;
std::cout << lastTwoDigit;
}
got error - "runtime error: signed integer overflow on line 'multiply = a * b * c * d;'"
*/
/*
Second Solution - Break down the calculations to avoid overflow.
int main()
{
long long a, b, c, d;
std::cin >> a >> b >> c >> d;
long long ab = a * b;
int mod1 = ab % 100;
long long cd = c * d;
int mod2 = cd % 100;
int multiply = mod1 * mod2;
int lastTwoDigit = multiply % 100;
std::cout << lastTwoDigit;
}
got error - wrong answer 1st lines differ - expected: '00', found: '0'
*/
/*
Another approach is to use modular arithmatic to shorten calculations and manage overflows.
*/
int main()
{
long long a, b, c, d;
std::cin >> a >> b >> c >> d;
long long ab = a * b;
int mod1 = ab % 100;
long long cd = c * d;
int mod2 = cd % 100;
int multiply = mod1 * mod2;
int lastTwoDigit = multiply % 100;
std::cout <<std::setw(2)<<std::setfill('0')<< lastTwoDigit;
}