[英]Find the number of common factors for n numbers excluding “1” as common factor
[英]What is the best algorithm to find number of factors of first N natural numbers?
我必須找到從2 to N
所有數字的因子總數。
這是我的方法。
運行Sieve of Eratosthenes
並獲得從2 to N
所有素數。
對於從2 to N
每個數,進行素因子化並獲得所有素因子的指數。 為每個素數因子指數加1
並乘以所有指數,即
N = 2^x1 * 3^x2 * 5*x^3 ...
然后,
Number of factors = (x1 + 1) * (x2 + 1) * (x3 + 1) ...
是否有任何替代/有效的方法可以有效地計算前N
自然數的因子總數。
2和N之間所有整數的因子數可以通過以下公式在O(N)中計算:
total = N/1 + N/2 + ... + N/N - 1. (integer division)
在2和N之間的任何特定整數x是2和N之間的以下整數的因子:x,2x,3x,4x,...,(N / x)x
例1,從2到6的數字的因子總數是13:6/1 + 6/2 + 6/3 + 6/4 + 6/5 + 6/6 - 1 = 6 + 3 + 2 + 1 + 1 + 1-1 = 13
These are the factors:
2: 1, 2
3: 1, 3
4: 1, 2, 4
5: 1, 5
6: 1, 2, 3, 6
2, 3, and 5 all have 2 factors, 4 has 3, and 6 has 4, for a total of 13.
如果你只想要素數因素:
total = N/p1 + N/p2 + ... + N/pk where pk is the largest prime <= N.
例如,N = 6:6/2 + 6/3 + 6/5 = 6
2: 2
3: 3
4: 2
5: 5
6: 2, 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.