백준 - 4375 1 c++ (모듈러연산 방식)

2025. 12. 5. 04:55·C++ 백준

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

해당 문제는 처음에 이렇게 풀었다

숫자를 직접 만들고 전부 계산하는방식으로 말이다

#include <iostream>
#include <string>

using namespace std;
int num;
int main()
{
	while (cin >> num)
	{
		string s = "1";
		while (true)
		{
			long long temp = 0;
			for (char c : s)
				temp = temp * 10 + (c - '0');

			if (temp % num == 0)
			{
				cout << s.size() << '\n';
				break;
			}
			s += "1";
		}
	}
	return 0;
}

 

그랬더니 오버플로우 + 시간초과가 나왔다

 

이럴떈 정수론의 "모듈러 연산" 을 사용하면된다

모듈러 연산의 공식은 이와 같다

 

  • ( a + b ) % n = ( a % n + b % n ) % n
  • ( a * b ) % n = ( a % n * b % n ) % n

모듈러 연산을 적용하면 이와같다

#include <iostream>

using namespace std;
int num;
long long cnt, temp;
int main()
{
	while (cin >> num)
	{
		int cnt = 1, temp = 1;
		while (true)
		{
			if (cnt % num == 0)
			{
				cout << temp << '\n';
				break;
			}
			else
			{
				//원래 공식 = cnt = cnt * 10 + 1;
				//모듈러 공식
				cnt = (cnt * 10 + 1) % num;
				temp++;
			}
		}
	}
	return 0;
}

 

피보나치 수열 같은 값이 엄청나게 커지는 경우라던가

연산이 엄청나게 반복될때 사용하면될꺼같다

 

저작자표시 비영리 변경금지 (새창열림)

'C++ 백준' 카테고리의 다른 글

백준 - 3986 좋은 단어 c++  (0) 2025.12.03
백준 - 1940 주몽 C++  (0) 2025.12.03
백준 (11655, 9996, 2559)  (0) 2025.11.16
'C++ 백준' 카테고리의 다른 글
  • 백준 - 3986 좋은 단어 c++
  • 백준 - 1940 주몽 C++
  • 백준 (11655, 9996, 2559)
lucodev
lucodev
커피와 노트북 그리고 개발
  • lucodev
    루코 개발테이블
    lucodev
  • 전체
    오늘
    어제
    • 분류 전체보기 (210) N
      • Unreal 프로젝트 다이어리 (107) N
        • 첫번째 프로젝트 (73)
        • 두번째 프로젝트 (34) N
      • Unreal 팁 (8)
      • Unreal 디버깅 (8)
      • C++ 프로그래머스 (52)
        • Stack,Queue (7)
        • Hash (4)
        • Heap (2)
        • Sort (5)
        • Exhaustive search (5)
        • Greedy (2)
        • BFS , DFS (7)
        • Graph (2)
        • Dynamic Programming (1)
        • C++ Math (2)
        • 기타 문제 (14)
      • C++ 백준 (4)
      • C++ 팁 (1)
      • 개인 코테 & 스타디 <비공개> (29)
        • 코드 개인보관함 (9)
        • 코딩테스트+@ (11)
        • 알고리즘 스타디 (6)
        • 알고리즘 스타디 과제 (3)
        • 비공개 (0)
  • 인기 글

  • 최근 글

  • 최근 댓글

  • 링크

  • 공지사항

  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 태그

    언리얼 behavior tree
    언리얼 인벤토리
    언리얼 파쿠르
    언리얼 컷씬
    언리얼 프로그래스바
    Unreal Parkour
    언리얼 behaviortree
    언리얼 상호작용
    언리얼
    unreal 시퀀스
    언리얼 ui
    언리얼 비헤이비어트리
    unreal 인벤토리
    언리얼 parkour
    언리얼 motionmatching
    unreal inventory
    unreal 모션매칭
    언리얼 모션매칭
    unreal 파쿠르
    언리얼 시퀀스
  • hELLO· Designed By정상우.v4.10.3
lucodev
백준 - 4375 1 c++ (모듈러연산 방식)
상단으로

티스토리툴바