Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To see how to find the factors of a given number in C# see <a href="https://stackoverflow.com/questions/239865/best-way-to-find-all-factors-of-a-given-number-in-c">this (duplicate?) StackOverflow question</a>.</p> <p>A few points on your code:</p> <ul> <li>there is no need for recursion if using a naive search, just build a list of factors within the method and return it at the end (or use <code>yield</code>).</li> <li>your second if statement is redundant as it wraps a while loop with the same condition.</li> <li>you should use an integer type (and unsigned integer types will allow larger numbers than their signed counterparts, e.g. <code>uint</code> or <code>ulong</code>) rather than <code>decimal</code> as you are working with integers. For arbitrarily large integers, use <code>System.Numerics.BigInteger</code>.</li> <li>if you search incrementally upwards for a factor, you can stop looking when you have got as far as the square root of the original number, as no factor can be larger than that.</li> </ul> <p>Also, note that there is no known efficient algorithm for factoring large numbers (see <a href="http://en.wikipedia.org/wiki/Integer_factorization" rel="nofollow noreferrer">Wikipedia</a> for a brief overview).</p> <p>Here's example code, based on the above observations:</p> <pre><code>static IList&lt;BigInteger&gt; GetFactors(BigInteger n) { List&lt;BigInteger&gt; factors = new List&lt;BigInteger&gt;(); BigInteger x = 2; while (x &lt;= n) { if (n % x == 0) { factors.Add(x); n = n / x; } else { x++; if (x * x &gt;= n) { factors.Add(n); break; } } } return factors; } </code></pre> <p>Note that this is still a rather naive algorithm which could easily be further improved.</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.
    1. VO
      singulars
      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