【发布时间】:2020-07-29 10:04:20
【问题描述】:
我发现了一个用 C 语言编写的算法,可以解决素数问题,但我不明白为什么我们有 i
// Program to print all prime factors
# include <stdio.h>
# include <math.h>
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n%2 == 0)
{
printf("%d ", 2);
n = n/2;
}
// n must be odd at this point. So we can skip
// one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i+2) // I don't get why i <= sqrt(n) here !??
{
// While i divides n, print i and divide n
while (n%i == 0)
{
printf("%d ", i);
n = n/i;
}
}
// This condition is to handle the case when n
// is a prime number greater than 2
if (n > 2)
printf ("%d ", n);
}
【问题讨论】:
-
因为
sqrt(i) * uncheckedprime > i -
如果您检查了小于或等于
sqrt(n)的n的所有因子,那么对于较高的因子(反之亦然),您会知道什么?如果p * q = n和p > sqrt(n),你对q了解多少? -
谢谢,我现在知道 n 至少有一个小于 sqrt(n) 的素数和一个大于 sqrt(n) 的素数,否则 n 是素数。
-
@Thang 不,不能保证合数的质因数大于
sqrt(n)。考虑16 == 2 * 2 * 2 * 2,它的质因数小于sqrt(16) == 4。 -
sqrt(n)在 C/C++ 中对于大数字可能会变得不精确,请考虑改用i*i <=n
标签: c algorithm primes factors prime-factoring