简体   繁体   中英

Prime factors generation C++

Here is what I have so far:

//project Eular Problem 4: Prime Factors
#include<iostream>
#include<cmath>
typedef unsigned long long int uint_64;
using namespace std;

void storeFactors(uint_64 factors[], uint_64 num)
{
    for(uint_64 i=0;i*i<num;i++
       factors[i]=1;       //assign 1 to all the values

    for(uint_64 j=2; j*j<num;j++){
       if(num%j!=0)
          factors[j]=0;       //assign 0 to non-factors
    } 
}  

//Sieve of Eratosthenes to generate primes
void gen_primes(uint_64 arr[],uint_64 firstElement, uint_64 lastElement, uint_64 size)
{
    for(uint_64 i=0;i<size;i++)   //assigning 1 to all the values
       arr[i]=1;

    for(uint_64 i=2;i*i<=lastElement;i++){   //loop until the square-root of n
       if(arr[i])
          for(uint_64 j=i;j*i<=lastElement;j++)      //eliminate multiples by assigning them 0
            arr[j*i]=0;
       if(firstElement==1)
          arr[firstElement]=0;
    }
}

void arrayComp(uint_64 factors[],uint_64 primeArray[], uint_64 size)
{
    for(uint_64 i=2; i<=size; i++){
        if(factors[i] && primeArray[i]){
                cout<<i<<endl;
        }
    }
}

void processFactors(uint_64 num)
{
    uint_64 size = sqrt(num);
    uint_64 *factors = new uint_64[size];
    uint_64 *primeArray = new uint_64[size];

    storeFactors(factors, num);
    gen_primes(primeArray, 2, num, size);
    arrayComp(factors, primeArray,size);

    delete [] factors;
    delete [] primeArray;
}

int main()
{
    uint_64 number;
    cout<<"Enter a number: "<<endl;
    cin>>number;
    cout<<"The prime factors of "<<number<<" are: "<<endl;
    processFactors(number);

    return 0;
}

I tried taking the sieve approach to calculate the factors. All the non factors are assigned 0. ArrayComp displays the numbers if they are both factors of the input and also prime.

The problem I'm having is that the output is not complete and the programs runs into a segmentation fault. For example, factors for 10 are 5 and 2, but it shows the same answer for 100.

EDIT: Another thing I'm not too confident of is the size of the array. This program shows 3 as the prime factor of 21 and not 7, but if I increase the size by 1, it shows 3 and 5(incorrect)

The prime factors of 100 are the same as the prime factors of 10, only the multiplicity is different.

It appears that your representation doesn't have any way to store repeated factors.

uint_64 size = sqrt(num);
uint_64 *factors = new uint_64[size];
uint_64 *primeArray = new uint_64[size];

wrong reserve size.

ex.)

num = 10

size = 3

factor of 10 = 2, 5

    if(factors[i] && primeArray[i]){
            cout<<i<<endl;
    }

factors[5] ? then array size is 3(0,1,2)

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