최대 공약수 구하는 법 (유클리드 호제법):
a,b의 최대공약수를 구한다고 할 때(단, a>b), a= bq + r로 나타낼 수 있고, a,b의 최대 공약수는 r과 b의 최대공약수와 같다. 따라서 r=0이 될 때까지 반복하면 b는 최대 공약수가 된다.
def gcd(bigger, smaller):
if not bigger > smaller:
bigger, smaller = smaller, bigger
'''둘의 크기 비교'''
while smaller != 0: ''' 새로운 r이 0이 될 때까지, 그때 공약수는 b'''
remainder = bigger % smaller '''나머지 r 구함'''
bigger, smaller = smaller, remainder ''' b와 r의 최대 공약수, 크기를 비교하여 새로운 a,b설정함 '''
return bigger
함수 생성 시
'''
기능
매개변수 설명
반환값
'''
def lcm (a,b):
'''최소공배수 계산'''
return a*b/gcd(a,b)
class Fraction:
def __init__(self,numerator, denominater=1):
self.numerator = numerator
self.denominator = denominater
@classmethod
def reduce_fraction(cls,f):
_gcd = gcd(f.numerator, f.denominator)
return cls(f.numerator//_gcd, f.denominator//_gcd)
def __add__(self,another):
if type(another) == int:
another = Fraction(another)
"""분수+정수"""
if type(another) == Fraction:
_lcm = lcm(self.denominator, another.denominator)
n_sum = lcm * self.numerator/self.denominator + \
_lcm * another.numerator/another.denominater
return Fraction(int(n_sum), _lcm)
else:
print('wrong type')
raise(TypeError)
def __eq__(self, another):
return self.numerator == another.numerator and \
self.denominator == another.denominator
def __str__(self):
return f'{self.numerator}/{self.denominator}'
if __name__ == '__name__':
f1 = Fraction(-2,6)
f2 = Fraction(2,4)
print(f'{f1}+{f2} = {Fraction.reduce_fraction(f1+f2)}')
컨테이너 자료형
'-' 카테고리의 다른 글
구조체 (0) | 2021.11.16 |
---|---|
자바스크립트 - 연산자, 조건문 (0) | 2021.11.12 |
문자/문자열 처리함수 (0) | 2021.11.09 |
자바스크립트 (0) | 2021.11.01 |
Chapter 7. Sampling Dist and the Central Limit Theorem(표본분포과 중심극한정리) - (1) 소개 (0) | 2021.11.01 |
댓글