본문 바로가기
Algorithm/📖Baekjoon

#1676 팩토리얼 0의 개수

by yewoneeee 2022. 8. 6.

# 문제

# 입력 및 출력

# 풀이

팩토리얼 계산할때 n이 대략 16 이상부턴 int형 범위를 넘어가게 된다

long long도 500 팩토리얼까진 계산할 수 없기 때문에 string으로 변환해서 계산해줘야한다

 

string 곱하기, 더하기 연산 코딩하기 귀찮아서 미루다가 오늘 해결했다

 

#include <iostream>
#include <string>
using namespace std;

string add(string a, string b) {
	int size = a.size() < b.size() ? b.size() : a.size();
	if (a.size() < b.size()) {
		for (int i = a.size(); i < size; i++) a = "0" + a;
	}
	else {
		for (int i = b.size(); i < size; i++) b = "0" + b;
	}
	int c = 0, r = 0;
	string result = "";
	for (int i = size - 1; i >= 0; i--) {
		r = a[i] + b[i] - 96 + c;
		c = r / 10;
		r %= 10;
		result = to_string(r) + result;
	}
	if (c != 0) result = to_string(c) + result;
	return result;
}

string mul(string a, string b) {
	string next = "", op = "";
	for (int i = b.size() - 1; i >= 0; i--) {
		int r = 0, c = 0;
		string result = "";
		for (int j = a.size() - 1; j >= 0; j--) {
			r = (a[j] - 48)*(b[i] - 48) + c;
			c = r / 10;
			r %= 10;
			result = to_string(r) + result;
		}
		if (c != 0) result = to_string(c) + result;
		result += next;
		next += "0";
		op = add(op, result);
	}
	return op;
}

int check(string res) { // 뒤에서부터 0이 몇개인지 확인
	int i = res.size() - 1, cnt = 0;
	while (res[i] == '0') {
		cnt++;
		i--;
	}
	return cnt;
}

int main() {
	int n;
	cin >> n;
	string res = "1";
	for (int i = 2; i <= n; i++) {
		res = mul(res, to_string(i));
	}
	cout << check(res) << "\n";
}

 

근데 다른 사람 제출물을 보니 코드가 매우 짧길래 찾아봤더니

따로 규칙이 있는 것 같다,,

if (tmp % 125 == 0)
	ans += 3;
else if (tmp % 25 == 0)
	ans += 2;
else if (tmp%5 == 0)
	ans += 1;

입력받은 n이 5보다 작아질때까지 해당 코드를 반복하면 된다

 

큰 수 덧셈, 곱셈 공부했다 치고 공식은 그냥 알고 넘어가기로 했다,,

'Algorithm > 📖Baekjoon' 카테고리의 다른 글

#3036 링  (0) 2022.08.10
#11659 구간 합 구하기 4  (0) 2022.08.08
#18352 특정 거리의 도시 찾기  (0) 2022.08.05
#1449 수리공 항승  (0) 2022.08.04
#1476 날짜 계산  (0) 2022.08.03

댓글