简体   繁体   中英

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. 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? 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.

So when you reach 9 you already removed all powers of 3 , so 9 never divides n at this point: the algorithm works

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)

I'm not sure if it's computing or maths.

But if i is composite it will never divide the current value of n . That's because all the prime factors of the composite number i have already been visited and 'divided out' of n .

9 is a special case. Any factors of 3 have been divided out so n%i==0 will never be true by the time i reaches 9.

Similarly when it reaches 15 the factors of 3 and 5 have been divided out and n%15==0 will be false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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