celina의 이것저것

[C++] 백준 1676번 - 팩토리얼 0의 개수 본문

자료구조&알고리즘/백준

[C++] 백준 1676번 - 팩토리얼 0의 개수

celinayk 2023. 3. 22. 14:18
반응형

문제

N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N이 주어진다. (0 ≤ N ≤ 500)

출력

첫째 줄에 구한 0의 개수를 출력한다.

접근

처음에 풀었던 코드는 이렇다

#define _CRT_SECURE_NO_WARNINGS
#include <iostream> 
#include <algorithm>
#include <string>
#include <vector>
#include <math.h>
#include <cmath>
#include <cstring>
using namespace std;
#define all(x) (x).begin(), (x).end() 


int main() {

    int n;
    scanf("%d", &n);
     

    //팩토리얼 구하기 3628800
    int result = 1;
    for (int i = n; i > 0; i--) {
        result *= i;
    }
    string str = to_string(result);
    int len = str.size();


    int cnt = 0;
    int idx = 0;
    for (int i = len - 1; i >= 0; i--) {
        if (str[i] != '0') {
            break;
        }
        cnt++;
    }
   
     printf("%d ", cnt);
    
    return 0;
}

제목 그대로 먼저 팩토리얼의 값을 구한다,

그리고 거꾸로 순회하면서 0일마다 카운팅을 해준후 0이 아닌 숫자를 만나면 반복문을 종료하도록 했다

문제 예시에 나와있는 것들도 문제 없이 잘 작동해서 당연히 정답인줄 알앗는데 틀렸음...ㅋ

솔직히 왜 틀렷는지 모르겟다.... 알려줄사람...

다른 사람들은 어떻게 풀었나 보니 전혀 다른 방법으로 풀었다 그래서 나도 그 방법을 써서

다시 풀었다 

코드

#define _CRT_SECURE_NO_WARNINGS
#include <iostream> 
#include <algorithm>
#include <string>
#include <vector>
#include <math.h>
#include <cmath>
#include <cstring>
using namespace std;
#define all(x) (x).begin(), (x).end() 


int main() {

    int n;
    scanf("%d", &n);


    int cnt = 0;
    while (n >= 5) {
        cnt += n/ 5;
        n /= 5;
    }

     printf("%d ", cnt);
    
    return 0;
}

 

이 게시글을 참조했다. 여기에 규칙이 있을줄은....

https://st-lab.tistory.com/165

 

[백준] 1676번 : 팩토리얼 0의 개수 - JAVA [자바]

www.acmicpc.net/problem/1676 1676번: 팩토리얼 0의 개수 N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오. www.acmicpc.net 문제 정말 정말 쉬운 문제다. 알고리

st-lab.tistory.com

출처 

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

 

1676번: 팩토리얼 0의 개수

N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오.

www.acmicpc.net

 

Comments