2017年12月19日 星期二

a010: 因數分解


a010: 因數分解
"""各位在國小時都學過因數分解,都瞭解怎麼樣用紙筆計算出結果,
現在由你來敎電腦做因數分解。
因數分解就是把一個數字,切分為數個質數的乘積,如 12=2^2 * 3

其中, 次方的符號以 ^ 來表示"""


def reduceNum(n):
    print ('{} = '.format(n),end='')
    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 range(2, n + 1) :
            if n % index == 0:
                n =int(n/ index) # n 等於 n/index
                if n == 1:
                    print (index)
                else : # index 一定是素數
                    print ('{} *'.format(index),end='')
                break




print("因數分解")

intX=int(input("請輸入數目  : "))

reduceNum(intX)

====================== RESTART: D:/Python_APSC/a010.py ======================
因數分解
請輸入數目  : 999997
999997 = 757 *1321
>>>
====================== RESTART: D:/Python_APSC/a010.py ======================
因數分解
請輸入數目  : 17
17 = 17
>>>

沒有留言:

張貼留言

WOKWI ESP32 LED Control , Node-Red MQTT SQLITE  

WOKWI ESP32 LED Control ,  Node-Red  MQTT SQLITE   const char broker[] = "test.mosquitto.org" ; //const char broker[] = "br...