【python】將一個正整數分解質因數


def reduceNum(n):
    '''題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5'''
    print '{} = '.format(n),
    if not isinstance(n, int) or n <= 0 :
        print 'Please input a valid number !'
        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 # let n equal to it n/index
                if n == 1: # This is the point
                    print index # The last one
                else : # index 一定是素數
                    print '{} *'.format(index),
                break
reduceNum(1250895)
reduceNum(23)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM