简体   繁体   English

找出一个数的所有质因数

[英]finding all prime factors of a number

This program calculates all factors of a no.该程序计算否的所有因素。 by first finding all prime factors and adding 1 to their exponents and then multiplying them amongst each other.首先找到所有质因数,然后将它们的指数加 1,然后将它们相乘。 But in the for loop i is incremented by 2 in every iteration.Isn't this wrong as after 7 it'll be incremented to 9 which isn't prime?但是在 for 循环中,我在每次迭代中都会增加 2。这是不是错误,因为在 7 之后它会增加到 9 这不是素数? Or am I wrong?还是我错了? Can anyone pls explain!谁能解释一下!

#include<bits/stdc++.h>
using namespace std;

int main() 
{
    int n,i;
    cin>>n;
    int factors=1,exponen=0;//exponent stores power of current prime
    while(n%2==0)//a separate check for 2       {
        exponen++;
        n=n/2;
    }
    factors= factors*(exponen+1);
    exponen=0;
    int original_n=n;
    for(i=3;n>1 && i<=sqrt(original_n);i+=2)//Checking for every prime number
    {
        exponen=0;
        while(n%i==0)
        {
            exponen++;
            n=n/i;
        }
        factors= factors*(exponen+1);
    }
    cout<< factors<< endl;
    return 0;
}
    while(n%i==0)
    {
        exponen++;
        n=n/i;
    }

that loop removes (and counts) all the i factors from n until there's none left.该循环从n删除(并计算)所有i因子,直到没有剩余。

So when you reach 9 you already removed all powers of 3 , so 9 never divides n at this point: the algorithm works因此,当您达到9您已经去除了3所有幂,因此此时9永远不会除以n :算法有效

Note: this method is not the most efficent one, looping on an actual prime number list generated using the sieve of Erathostenes could speed that up since there are no tests on every odd number, only on the primes (the loop cannot be as easily avoided, though)注意:此方法不是最有效的方法,循环使用 Erathostenes 筛生成的实际素数列表可以加快速度,因为没有对每个奇数进行测试,仅对素数进行测试(循环不能那么容易避免, 尽管)

I'm not sure if it's computing or maths.我不确定它是计算还是数学。

But if i is composite it will never divide the current value of n .但是如果i是复合的,它永远不会除以n的当前值。 That's because all the prime factors of the composite number i have already been visited and 'divided out' of n .那是因为合数i所有质因数都已经被访问过并“除”了n

9 is a special case. 9是特例。 Any factors of 3 have been divided out so n%i==0 will never be true by the time i reaches 9.任何 3 的因数都被除掉了,所以当i达到 9 时n%i==0永远不会为真。

Similarly when it reaches 15 the factors of 3 and 5 have been divided out and n%15==0 will be false.类似地,当它达到 15 时,3 和 5 的因数已被除掉, n%15==0将为假。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM