[파이썬] 몫과 나머지

미음제

·

2022. 1. 3. 18:55

몫과 나머지 구하기

 

x = 5
print(5/2)      # 2.5

 

5라는 숫자를 2로 나눌 때 "/" 기호를 사용해 나누게 된다. 이 경우 5를 2로 나눈 2.5가 출력된다.

나머지를 구하기 위해서 사용하는 기호는 "%"이다. 몫을 구할때는 "/"를 한 개 더 쓰면 된다.

 

x = 5
print(5/2)      # 2.5

print(5 // 2)   # 2
print(5 % 2)    # 1

 

5 // 2의 경우 5를 2로 나눈 몫이 나오고, 5 % 2의 경우 5를 2로 나눈 나머지가 나온다.

 

divmod()

 

파이썬에서는 divmod라는 내장 함수가 존재하는데, 이 함수는 두 숫자를 인자로 받아 첫 번째 인자를 두 번째 인자로 나눈 몫과 나머지를 tuple 형식으로 return 해주는 함수이다.

 

divmod(a, b)
Take two (non-complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. With mixed operand types, the rules for binary arithmetic operators apply. For integers, the result is the same as (a // b, a % b). For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).
divmod(a,b) 두 개의 (복소수가 아닌) 숫자를 인수로 취하고 정수 나누기를 사용할 때 몫과 나머지로 구성된 숫자 쌍을 반환합니다. 혼합 피연산자 유형의 경우 이진 산술 연산자에 대한 규칙이 적용됩니다. 정수의 경우 결과는 (a // b, a % b)와 같습니다. 부동 소수점 숫자의 경우 결과는 (q, a % b)입니다. 여기서 q는 일반적으로 math.floor(a / b)이지만 그보다 1 작을 수 있습니다. 어쨌든 q * b + a % b는 a에 매우 가깝고, a % b가 0이 아니면 b와 같은 부호를 가지며 0 <= abs(a % b) < abs(b)입니다.

 

5라는 숫자를 2로 나눌 때 divmod() 함수를 사용하면 다음과 같다.

 

print(divmod(5,2)) #(2, 1)

 

몫과 나머지가 tuple의 형식으로 return 된다. divmod()를 사용할 때, 두 번째 인자로 0을 사용하면 안 된다.

 

print(divmod(5,2)) #(2, 1)
print(divmod(5,0)) #ZeroDivisionError: integer division or modulo by zero

 

//, % 연산과 divmod() 함수 중 더 빠른 것은?

 

몫과 나머지를 모두 구해야 하는 경우에서 divmod() 함수가 "%"와 "//" 연산자를 사용하는 것보다 성능적으로 나은지 물어본다면 숫자에 따라 다르게 나타난다.

 

숫자가 작은 경우일 때 //, % 연산자가 유리하고, 숫자가 큰 경우일 때 divmod() 함수가 유리하다.

 

https://stackoverflow.com/questions/30079879/is-divmod-faster-than-using-the-and-operators

 

Is divmod() faster than using the % and // operators?

I remember from assembly that integer division instructions yield both the quotient and remainder. So, in python will the built-in divmod() function be better performance-wise than using the % and //

stackoverflow.com

 


 

몫과 나머지 예제

 

예제 1

 

 

코딩테스트 연습 - 3진법 뒤집기

자연수 n이 매개변수로 주어집니다. n을 3진법 상에서 앞뒤로 뒤집은 후, 이를 다시 10진법으로 표현한 수를 return 하도록 solution 함수를 완성해주세요. 제한사항 n은 1 이상 100,000,000 이하인 자연수

programmers.co.kr

 

예제 1 풀이

 

 

3진법 뒤집기 · mieumje/Python_Coding_Test@89f3e9f

Permalink This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository. Browse files 3진법 뒤집기 Loading branch information Showing 1 changed file with 40 additions and 0 deletions. +40 −0 Level1_

github.com

 

예제 2

 

 

코딩테스트 연습 - [1차] 비밀지도

비밀지도 네오는 평소 프로도가 비상금을 숨겨놓는 장소를 알려줄 비밀지도를 손에 넣었다. 그런데 이 비밀지도는 숫자로 암호화되어 있어 위치를 확인하기 위해서는 암호를 해독해야 한다. 다

programmers.co.kr

 

예제 2 풀이

 

 

Feat : [1차] 비밀지도 · mieumje/Python_Coding_Test@446f5a4

정확성 테스트 테스트 1 〉 통과 (0.06ms, 10.3MB) 테스트 2 〉 통과 (0.17ms, 10.3MB) 테스트 3 〉 통과 (0.01ms, 10.3MB) 테스트 4 〉 통과 (0.08ms, 10.3MB) 테스트 5 〉 통과 (0.04ms, 10.2MB) 테스트 6 〉 통과 (0.11ms, 10.3

github.com

 

반응형