Note that there are some explanatory texts on larger screens.

plurals
  1. POPrime factors generation C++
    primarykey
    data
    text
    <p>Here is what I have so far: </p> <pre><code>//project Eular Problem 4: Prime Factors #include&lt;iostream&gt; #include&lt;cmath&gt; 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&lt;num;i++ factors[i]=1; //assign 1 to all the values for(uint_64 j=2; j*j&lt;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&lt;size;i++) //assigning 1 to all the values arr[i]=1; for(uint_64 i=2;i*i&lt;=lastElement;i++){ //loop until the square-root of n if(arr[i]) for(uint_64 j=i;j*i&lt;=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&lt;=size; i++){ if(factors[i] &amp;&amp; primeArray[i]){ cout&lt;&lt;i&lt;&lt;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&lt;&lt;"Enter a number: "&lt;&lt;endl; cin&gt;&gt;number; cout&lt;&lt;"The prime factors of "&lt;&lt;number&lt;&lt;" are: "&lt;&lt;endl; processFactors(number); return 0; } </code></pre> <p>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.</p> <p>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.</p> <p>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)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload