Python includes exercises 14
Title: a positive integer decomposition of the quality factor. For example: Enter 90 to print out 90 = 2 * 3 * 3 * 5.
Program analysis: the decomposition of n quality factor, you should first find a smallest prime number k, then according to the following steps:
(1) If the prime number exactly equal to n, then the decomposition of the quality factor of the process has ended, you can print out.
(2) if n <> k, k but n be divisible should print out the value of k, k with n divided by the quotient, you as a new positive integer n, repeat the first step.
(3) if n is not divisible by k, k + 1 is used as the value of k, repeat the first step.
Source Code:
#!/usr/bin/python # -*- 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 reduceNum(90) reduceNum(100)
The above example output is:
90 = 2 * 3 * 3 * 5 100 = 2 * 2 * 5 * 5