將一個正整數分解質因數
#!/bin/env python2
# -*- coding: UTF-8 -*-
def reduceNum(n):
print '{} = '.format(n),
if not isinstance(n, int) or n <= 0 :
print '請輸入一個正確的數字 !'
exit(0)
elif n in [1] :
print '{}'.format(n)
while n not in [1] : # 迴圈保證遞迴
for index in xrange(2, n + 1) :
if n % index == 0:
n /= index # n 等於 n/index
if n == 1:
print index
else : # index 一定是素數
print '{} *'.format(index),
break
輸出乘法口訣表
#!/bin/env python2
# -*- coding: UTF-8 -*-
for i in range(1, 10):
print
for j in range(1, i+1):
print "%d*%d=%d" % (i, j, i*j),
輸出斐波那契數
#!/bin/env python2
# -*- coding: UTF-8 -*-
def fib(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)