Skip to main content

2-8 常見程式範例

氣泡排序法(Bubble Sort Algorithm)

array=[5,3,4,6,9,1,7,2,0,8]
def BubbleSort(data):
  n = len(data)
  for i in range(n - 1):
    for j in range(n - 1 - i):
      if data[j] > data[j+1]:
        temp = data[j]
        data[j] = data[j+1]
        data[j+1] = temp
  return data

print(BubbleSort(array))

找出質數

lower = 100
upper = 200
for num in range(lower, upper+1):
  if num > 1:
    for i in range(2, num):
      if num % i == 0:
        break
    else:  #for 搭配else 會在跑完迴圈最後一圈之後執行else裡面的程式
        print(num)

最小公倍數 (Least Common Mutiple, LCM)

def LCM(num1, num2):
if num1 > num2: #找出兩個數之中較大者
greater = num1
else:
greater = num2
while True:
if (greater % num1 == 0 ) and (greater % num2 == 0): #都能被兩個數整除
break
greater += 1
return greater

n1 = int(input("請輸入第一個數字:"))
n2 = int(input("請輸入第二個數字:"))

print("最小公倍數 = " , LCM(n1, n2))