如何求N以内的约数总数?
给定数字 N,必须找到所有 i 的除数,其中 i>=1 且 i<=N。无法弄清楚。我必须使用质因数分解吗?限制为 N<=10^9 示例输出:
1 --> 1
2 --> 3
3 --> 5
4 --> 8
5 --> 10
6 --> 14
7 --> 16
8 --> 20
9 --> 23
10 --> 27
11 --> 29
12 --> 35
13 --> 37
14 --> 41
15 --> 45
Given a number N, have to find number the divisors for all i where i>=1 and i<=N. Can't figure it out.Do I have to this using prime factorization? Limit is N<=10^9
Sample Output:
1 --> 1
2 --> 3
3 --> 5
4 --> 8
5 --> 10
6 --> 14
7 --> 16
8 --> 20
9 --> 23
10 --> 27
11 --> 29
12 --> 35
13 --> 37
14 --> 41
15 --> 45
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要加快计算速度,请使用以下伪代码:
sum = 0; u = 地板(sqrt(N)); foreach k <= u, sum += Floor(N / K); sum = 2*sum-u*u
上述公式是由 Peter Gustav Lejeune Dirichlet 在 19 世纪给出的。
我使用上述算法编写了一个 C 程序,在我的计算机上计算从 1 到 10^14 的除数数量之和需要 0.118 秒。答案是3239062263181054。
To compute much faster, use the following Pseudocode:
sum = 0; u = floor(sqrt(N)); foreach k <= u, sum += Floor(N / K); sum = 2*sum-u*u
The above formula is given by Peter Gustav Lejeune Dirichlet in 19th Century.
I have written a C program using above algorithm and it takes 0.118 second on my computer to compute sum of number of divisors from 1 upto 10^14. The answer is 3239062263181054.
如果您想求给定 N 以内的所有除数之和,则不需要任何因式分解。您可以通过这种方式(例如)使用独特的循环来做到这一点。
从2开始,2是2*2、3*2、4*2等的约数。这给出了背后的想法。
Foreach k < N, Floor(N / k) 是 k 是某个 << 的除数的次数。 N.
伪代码:
总和= 0; foreach k <= N sum += Floor(N / K)
请注意,这与询问给定 N 的除数数量不同。
if you want to find the sum of all divisors up to a given N, you don't need any factoring. You can do it (for example) in this way, with a unique loop.
Start with 2, 2 is a divisor of 2*2, 3*2, 4*2 and so on. This gives the idea behind.
Foreach k < N, Floor(N / k) is the number of how many times k is a divisor of something < N.
Pseudocode:
sum = 0; foreach k <= N sum += Floor(N / K)
Note that this is not the same thing like asking for the number of divisors of a given N.
不确定您使用的是什么语言,但基本思想如下:
注意:
您只想计算 N mod i = 的结果0,因为这些是 i 进入 N 且没有余数的唯一实例;我认为这就是你的老师说“除数”时的意思——没有余数
。 For 循环的编写方式可能与您使用的语言略有不同。上面的代码是 VB。但是如果您查看书籍索引,您可能会发现这两个常见功能的语言版本。
..)并且 strong>编辑
好的——在这种情况下,只需添加另一个 FOR 循环,如下所示:
Not sure what language you're using, but here's the basic idea:
Notes:
You only want to count the results where N mod i = 0, because those are the only instances where i goes into N with no remainder; which I think is what your teacher probably means when they say 'divisor' -- no remainder.
The variable declarations (dim...) and the For loop might be written slightly differently in whatever language you're using. The code above is VB. But if you look in your book index, you'll probably find your language's version of these two common features.
EDIT
OK -- in that case, just add another FOR loop, as follows: