Skip to content
CatBus

Tag: number theory

All the articles with the tag "number theory".

BOJ1241GOLD 5
from collections import Counter, defaultdict

input = sys.stdin.readline
print = sys.stdout.write

N = int(input())

students = [int(input()) for _ in range(N)]
MAX_STUDENT = max(students) + 1

counter = Counter(students)
toktok = defaultdict(int)

for i in range(1, MAX_STUDENT):
    for j in range(i, MAX_STUDENT, i):
        if j in counter:
            toktok[j] += counter[i]

print("\n".join(str(toktok[s] - 1) for s in students) + "\n")

머리 톡톡

백준 1241번 '머리 톡톡' (골드 5) 문제 풀이. math, number theory, primality test 로 접근했다.

2025.07.03·1분·math
BOJ3036SILVER 4
ring = list(map(int, input().split()))
first = ring[0]
rings = ring[1:]
def gcd(a, b):
    while a % b != 0:
        r = a % b
        a, b = b, r
    return b

for r in rings:
    if first % r == 0:
        print(f"{first // r}/1")
    elif r % first == 0:
        print(f"1/{r // first}")
    else:
        g = gcd(first, r)
        print(f"{first // g}/{r // g}")

링

백준 3036번 '링' (실버 4) 문제 풀이. math, number theory, euclidean algorithm 로 접근했다.

2022.11.22·3분·math
BACKGROUNDEuclidean

a,b∈Za, b \in \mathbb{Z}이고 aa를 bb로 나눈 나머지를 rr이라 하자. (b≤a,0≤r≤bb \leq a, 0 \leq r \leq b)

a,ba, b의 최대 공약수를 (a,b)(a, b)라고 하면, 다음이 성립한다.

(a,b)=(b,r)(a, b)=(b, r)

출처: wikipidia

rr이 0이 될 때 알고리즘을 멈추며, 이 때의 bb가 최대공약수가 된다.

예를 들어 1460과 1037에 대해 알고리즘을 진행해보면 다음과 같다.

\begin{flalign*} (1460, 1037)\\=(1037, 323)\\=(323, 68)\\=(68, 52)\\=(52, 16)\\=(16, 4)\\=(4,0) \end{flalign*}

rr이 0일때 bb가 4이므로 1460과 1037의 최대공약수는 4이다.

유클리드 호제법

유클리드 호제법은 2개의 자연수에 대해 최대공약수를 구하는 알고리즘이며 다음과 같은 성질을 통해 알고리즘을 진행한다.

2022.11.22·1분·math
BOJ1037BRONZE 1
div = list(map(int, input().split()))
min, max = float('inf'), float('-inf')
for d in div:
    if min > d : min = d
    if max < d : max = d
print(min * max)

약수

백준 1037번 '약수' (브론즈 1) 문제 풀이. math, number theory 로 접근했다.

2022.11.15·2분·math
BOJ10610SILVER 5
nums = str(sys.stdin.readline().strip())
if '0' not in nums:
    print(-1)
else:
    l = [0] * (int(max(nums)) + 1)
    s = ''
    sum = 0
    for i in nums:
        l[int(i)] += 1
    for i in range(len(l)-1, 0, -1):
        s += str(i) * l[i]
        sum += i * l[i]
    if sum % 3 == 0: print(int(s) * (10 ** l[0]))
    else: print(-1)

30

백준 10610번 '30' (실버 5) 문제 풀이. math, string, greedy algorithm 로 접근했다.

2022.02.04·3분·math