要想做到python语言求因数方法,首先要明白其中的原理:
1、对由123456789这九个数字组成的9位数进行分解质因数。
2、123457698=2x3x3x7x13x23x29x113,所以他的值因数是113。
3、总共有362880种可能,从中找出值因数中最小的数字和值因数中数。
好了,下面来看看python语言求因数方法的实现源码:
#coding:utf-8import mathdef generator(count, s):if count == 1:for i in s:yield ielse:for i in s:_ = set(s)_.remove(i)for _ in generator(count-1, _):yield _ * 10 + iprimes = [2, 3] def prime(idx):if idx < len(primes):return primes[idx]new = primes[-1]+2while True:for i in primes:if new % i == 0:breakelse:primes.append(new)breaknew += 2return prime(idx)def probe(number, idx, value=0):if value > number:return valuep = prime(idx)sqrt = math.sqrt(number)while number % p != 0 and sqrt >= p:idx += 1p = prime(idx)if sqrt < p:return numberreturn probe(number/p, idx, max(p, value)) if __name__ == '__main__':_min = 10000000000, 10000000000_max = 0, 0for number in generator(9, set(range(1, 10))):maxfactor = probe(number, 0)if maxfactor < _min[0]:_min = maxfactor, [number]elif maxfactor == _min[0]:_min[1].append(number)if maxfactor > _max[0]:_max = maxfactor, [number]elif maxfactor == _max[0]:_max[1].append(number)print _minprint _max