문제) 백준 - 분항정복을 이용한 거듭제곱 - 곱셈
-> www.acmicpc.net/problem/1629
1629번: 곱셈
첫째 줄에 A, B, C가 빈 칸을 사이에 두고 순서대로 주어진다. A, B, C는 모두 2,147,483,647 이하의 자연수이다.
www.acmicpc.net
중간에 c로 나누어서 수를 작게 만드는게 핵심인 문제. 계산해야할 지수가 홀수,짝수로 나누어 지수법칙 적용.
C++ 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
#define endl "\n" | |
#define ll long long | |
using namespace std; | |
ll solve(ll a, ll b, ll c) { | |
//기저 사례 처리 | |
if (b == 0) return 1; | |
ll ret = solve(a, b / 2, c); | |
if (b % 2 == 1) return ((ret * ret) % c) * a % c; | |
else return (ret * ret) % c; | |
} | |
int main() { | |
ios::sync_with_stdio(false); | |
cout.tie(0); cin.tie(0); | |
ll a, b, c; | |
cin >> a >> b >> c; | |
cout << solve(a % c, b, c) << endl; | |
return 0; | |
} |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 2503번 - 숫자야구 (C++) 문제 및 풀이 (0) | 2021.04.13 |
---|---|
[백준] 2579번 - 계단 오르기(C++/파이썬) 문제 및 풀이 (0) | 2021.04.09 |
[백준] 2217번 - 로프 (파이썬/C++) 문제 및 풀이 (0) | 2021.04.05 |
[백준] 11726번 - 2xn 타일링 (파이썬/C++) 문제 및 풀이 (0) | 2021.03.30 |
[백준] 1005번 - ACM Craft (파이썬) 문제 및 풀이 (0) | 2021.03.30 |
댓글