【问题标题】:Algorithms to find prime factors寻找质因数的算法
【发布时间】: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 &gt; i
  • 如果您检查了小于或等于sqrt(n)n 的所有因子,那么对于较高的因子(反之亦然),您会知道什么?如果p * q = np &gt; 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 &lt;=n

标签: c algorithm primes factors prime-factoring


【解决方案1】:

为什么我们有 i

假设你需要找到9的因数,写成如下:

1 * 9  = 9
3 * 3  = 9

// 9 * 1 = 9 but it is the same case as first

从上面你可以看到,只要你到达3 * 3所在的行,你就不需要进一步探索了。请注意,3 是 9 的平方根。 对于 9,因数是 1,3,9。

下一个例子 36:

1 * 36 = 36
2 * 18 = 36
3 * 12 = 36
4 * 9 = 36
6 * 6 = 36
// No need to go further as the digits will repeat

在平方根 6 之后再次看到,我们不需要进一步探索,因为它不会给我们新的数字作为因素。 从上面看,6 的因数:1,2,3,4,6,9,12,18,36。质因数是 2,3。

在上面的两个例子中,我以完美的正方形为例。让我们举一个不同的例子,它不是一个完美的正方形,例如 24: 24的平方根是4点。所以我们会看到我们必须在 4 点停下来。

1 * 24 = 24
2 * 12 = 24
3 * 8  = 24
4 * 6  = 24

// Stop not process further
// Even if proceeded the next line would be 6 * 4 = 24 but we have already obtained these numbers.

因此我们停在 sqrt(24)。

总结: 对于'n',如果我们无法在sqrt(n) 之前找到一个素数,那么可以保证sqrt(n) 之上的数字不会包含n 的任何素数。

【讨论】:

  • (已编辑)在这里使用素数作为示例要好得多。收益就是这种情况。而你为 24 展示的并不是算法的工作原理。它将较小的因素分开,所以它变成 n=24: {print 2; n=12}, {打印 2; n=6},{打印 2,n=3},循环,i = 3,(i sqrt(3)) 为假,STOP_LOOP,3 > 2 为真,{打印 3 }.
  • 好的,谢谢,我已经解释了代码背后的概念。如果我选择一个完美的素数作为例子,那么逻辑可能不会很清楚。在看到 9、36 和 24 上的示例后,OP 可以立即想到如何将逻辑应用于素数或实际上任何数字。
  • 没有。它仅适用于素数。重新阅读我的评论。干杯,:)
猜你喜欢
  • 2018-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
相关资源
最近更新 更多