我有一個Python列出了一些主要因素。我如何(以Python方式)找到所有因素?
相反,指數(shù)清單,考慮簡單地 重復 利用的次數(shù)每一個素因子它 是一個因素。然后,處理生成primefactors的帶有重復的列表,itertools.combinations即可滿足您的需要-您只需要將長度2 len(primefactors) - 1的組合包含在所包含的項目中(只有一個的組合是主要因素,所有其中一個將是原始編號-如果您也想要這些編號,請使用range(1, len(primefactors) + 1)而不是range(2,len(primefactors))我的主要建議所使用的編號)。
結果中將存在重復(例如,6將出現(xiàn)的結果是的兩倍12,因為后者primefactors將是[2, 2,3]),并且當然可以按照通常的方式(sorted(set(results))例如)清除它們。
要計算primefactors給定listofAllPrimes,請考慮以下示例:
def getprimefactors(n): primefactors = [] primeind = 0 p = listofAllPrimes[primeind] while p <= n:if n % p == 0: primefactors.append(p) n //= pelse: primeind += 1 p = listofAllPrimes[primeind] return primefactors解決方法
我正在研究需要對整數(shù)進行因子分解的Euler項目。我可以列出所有給定數(shù)字的質數(shù)的列表。算術基本定理意味著我可以使用此列表來得出數(shù)字的 每個 因子。
我當前的計劃是將基本質數(shù)列表中的每個數(shù)字取整并提高其冪,直到找到每個質數(shù)的最大指數(shù)不再是整數(shù)因子為止。然后,我將乘以素數(shù)對的所有可能組合。
例如,對于180:
Given: prime factors of 180: [2,3,5]Find maximum exponent of each factor: 180 / 2^1 = 90 180 / 2^2 = 45 180 / 2^3 = 22.5 - not an integer,so 2 is the maximum exponent of 2. 180 / 3^1 = 60 180 / 3^2 = 20 180 / 3^3 = 6.6 - not an integer,so 2 is the maximum exponent of 3. 180 / 5^1 = 36 180 / 5^2 = 7.2 - not an integer,so 1 is the maximum exponent of 5.
接下來,對所有這些組合進行最大冪運算以得到因子:
2^0 * 3^0 * 5^0 = 1 2^1 * 3^0 * 5^0 = 2 2^2 * 3^0 * 5^0 = 4 2^0 * 3^1 * 5^0 = 3 2^1 * 3^1 * 5^0 = 6 2^2 * 3^1 * 5^0 = 12 2^0 * 3^2 * 5^0 = 9 2^1 * 3^2 * 5^0 = 18 2^2 * 3^2 * 5^0 = 36 2^0 * 3^0 * 5^1 = 5 2^1 * 3^0 * 5^1 = 10 2^2 * 3^0 * 5^1 = 20 2^0 * 3^1 * 5^1 = 15 2^1 * 3^1 * 5^1 = 30 2^2 * 3^1 * 5^1 = 60 2^0 * 3^2 * 5^1 = 45 2^1 * 3^2 * 5^1 = 90 2^2 * 3^2 * 5^1 = 180
因此,因子列表= [1、2、3、4、5、6、9、10、12、15、18、20、30、36、45、60、90、180]
這是我到目前為止的代碼。有兩個問題:首先,我認為這完全不是Python語言。我想解決這個問題。其次,我 真的沒有Python方式可以完成第二步。出于恥辱,我使您擺脫了荒謬的循環(huán)。
n是我們要分解的數(shù)字。listOfAllPrimes是不超過1000萬個素數(shù)的預先計算的列表。
def getListOfFactors(n,listOfAllPrimes): maxFactor = int(math.sqrt(n)) + 1 eligiblePrimes = filter(lambda x: x <= maxFactor,listOfAllPrimes) listOfBasePrimes = filter(lambda x: n % x ==0,eligiblePrimes) listOfExponents = [] #(do I have to do this?) for x in listOfBasePrimes:y = 1while (x**(y+1)) % n == 0: y += 1listOfExponents.append(y)
相關文章:
1. ASP基礎入門第八篇(ASP內(nèi)建對象Application和Session)2. ASP刪除img標簽的style屬性只保留src的正則函數(shù)3. jsp實現(xiàn)登錄驗證的過濾器4. Jsp中request的3個基礎實踐5. ASP常用日期格式化函數(shù) FormatDate()6. 解析原生JS getComputedStyle7. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法8. jsp+servlet簡單實現(xiàn)上傳文件功能(保存目錄改進)9. ASP基礎知識Command對象講解10. 輕松學習XML教程
