https://www.acmicpc.net/problem/1629
이 문제 풀었는데 아래 첫번ㅉㅐ 코드로 하니까 틀렸고 그래서 두 번째 코드로 풀었는데 맞더라구 두 코드 차이가 뭐야? 내가 봤을 때 똑같아 보여 ㅠㅠ
첫 번째 코드
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int a, b, c; int func(int x) { if (x == 1) return a % c; int res = func(x / 2) % c; if (x % 2 == 0) return res * res ; else return res * res * (a % c); } int main() { cin >> a >> b >> c; cout << func(b); } |
두 번째 코드
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include<iostream> using namespace std; int a, b, c; int func(int x) { if (x == 1) return a % c; int res = func(x / 2); if (x % 2 == 0) return res * res % c; else return res * res * a % c; } int main() { cin >> a >> b >> c; cout<< func(b); } |
res * res * a % c는 계산 후 c보다 작음이 보장되지만 res * res * (a % c)는 a % c * res * res이기 때문에 계산 후 c보다 작음이 보장되지 않는다 이게 오버플로우를 일으키면?
왜 보장이 안댐?? res = func(x/2) % c 면 보장 되는거아님??
첫번째껀 괄호 때문에 mod가 안됨
엥 왜여?
3*3%9랑 3*(3%9)랑 비교해보셈 - dc App
아 모듈러 분배법칙이 (3*3)%9 = (3%9) *(3%9) 이렇게 같은줄 알았는데 (3%9) * (3%9) % 9 이게 같은거였네.. 답변 달아주신 분들 감사합니다
첫 번째 코드는 12번째 줄에서 오버플로우