Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ int array pointers recursively to find prime factors
    primarykey
    data
    text
    <p>I am trying to make a function that can return the prime factors of a given number in an array (or multi-set, but I'm trying to use an array).</p> <p>For example, if I put in 12, I want to get 2, 2, and 3, not 2, and 3 like with a set. This is so that I can use these to see if it is a <a href="http://en.wikipedia.org/wiki/Smith_number" rel="nofollow">Smith number</a> or not, so I need the numbers seperately.</p> <p>Also, I am taking a recursive approach.</p> <p>I have tried (to no avail) to return the array many ways, including passing an initial pointer into the code which points to a space to store the array.</p> <p>I've tried just initializing the array in the function and then returning it.</p> <p>From what I can tell, I can get the array back from the base case iteration and then when trying to construct a new array with size <code>oldArray+1</code> to copy values to, things get messy. This is where I get lost.</p> <p>From what I've read, although this isn't the most efficient implementation, I should be able to make it work.</p> <p>I have a function, <code>nextPrime(int n)</code>, which given <code>n</code> will give back the next prime up from that number.</p> <p>See source below:</p> <pre><code>int* find(int n, int p) { int root = (int) floor(sqrt(n)); if (p &gt; root) { // Base case, array gets initialized and returned // depending on value of n and p. if (n &gt; 1) { factors = new int[1]; factors[0] = n; return factors; } else { factors = new int[0]; return factors; } } else if (n%p == 0){ // Inductive step if p is a factor int newFloor = (int) floor(n/p); factors = find(newFloor, p); // Initialize new array. int* newFactors; newFactors = new int[(sizeof(factors) / sizeof(int)) + 1]; // Add p to first slot, fill rest with contents of factors. factors[0] = p; for (int i = 0; i &lt; (sizeof(factors) / sizeof(int)); i++) { newFactors[i+1] = factors[i]; } return newFactors; } else { // Inductive step p isn't a factor of n factors = find(n, factors, nextPrime(p)); return factors; } } </code></pre> <p>As I say, the error is with returning the array and using its value, but why does it seem to return OK from the first iteration?</p>
    singulars
    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.
    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