# 생각

시간복잡도 : b가 계속 절반씩 깎이기 때문에 O(logb) 이다

a^n * a^n = a^2n의 성질을 이용하면 b가 최대 20억이라도 해결이 가능하다

 

 

# 전체 코드

#include <bits/stdc++.h>
using namespace std;
using LL = long long;

LL Power(LL a, LL b, LL c)
{
	if (b == 1)	// base condition
	{
		return a % c;
	}
	LL result = Power(a, b / 2, c);
	result = result * result % c;

	if (b % 2 == 0)	// 짝수면 바로 반환
	{
		return result;
	}
	else	// 홀수면 a 한 번 더 곱해서 반환
	{
		return result * a % c;
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	LL a, b, c;
	cin >> a >> b >> c;
	cout << Power(a, b, c);
}

https://www.acmicpc.net/problem/1629

 

1629번: 곱셈

첫째 줄에 A, B, C가 빈 칸을 사이에 두고 순서대로 주어진다. A, B, C는 모두 2,147,483,647 이하의 자연수이다.

www.acmicpc.net

'Algorithm > BOJ' 카테고리의 다른 글

[BOJ] 1074_Z with cpp  (0) 2022.01.27
[BOJ] 11729_하노이 탑 이동 순서 with cpp  (0) 2022.01.27
[BOJ] 5427_불 with cpp  (0) 2022.01.25
[BOJ] 6593_상범 빌딩 with cpp  (0) 2022.01.23
[BOJ] 2468_안전 영역.cpp  (0) 2022.01.23

+ Recent posts