exercise-17

Test :

  1. DRY : Don’t Repeat Yourself.
  2. The use of function :
    • To reduce the amount of code.
    • To make fixing the debug easier.
    • To make easier to read.

Try :

  1. Use function to act as pow(a, b) = a**b

    1
    2
    3
    4
    5
    6
    7
    8
    def power(x, y):
    result = 1
    for i in range(y):
    result *= x

    return result

    print(power(3,5))
  2. Greatest Common Divisor (gcd)

    gcd(x, y) = gcd(y, x mod y)

    Euclidean algorithm (辗转相除法)

    for example :

    | 168 | 63 | | |
    | ——– | —– | —- | ——– |
    | 168 | 63 | 42 | 余数0 |
    | 63 | 42 | 21 | gcd = 21 |
    | 263+ 42 | 42+21 | 242 | |

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    def gcd(x, y):
    while y:
    t = x%y
    x = y
    y = t

    return x

    x = int(input('Pls input an integer x:'))
    y = int(input('Pls input an integer y:'))
    print(gcd(x,y))
  3. Turn decimal system to binary system.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    def DectoBin(dec):
    temp = [ ]
    result = ' '

    while dec:
    quo = dec % 2
    dec = dec // 2
    temp.append(quo)

    while temp:
    result += str(temp.pop())

    return result

    Dec = int(input('Pls input an integer:'))
    print('Bin =', DectoBin(Dec))