Note that there are some explanatory texts on larger screens.

plurals
  1. POBest way to find all factors of a given number
    text
    copied!<p>All numbers that divide evenly into x.</p> <p>I put in 4 it returns: 4, 2, 1</p> <p>edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data.</p> <p>edit++: This is what I went with after all the help from everyone. Thanks again!</p> <p>edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results.</p> <pre><code>static IEnumerable&lt;int&gt; GetFactors2(int n) { return from a in Enumerable.Range(1, n) where n % a == 0 select a; } private IEnumerable&lt;int&gt; GetFactors3(int x) { for (int factor = 1; factor * factor &lt;= x; factor++) { if (x % factor == 0) { yield return factor; if (factor * factor != x) yield return x / factor; } } } private IEnumerable&lt;int&gt; GetFactors1(int x) { int max = (int)Math.Ceiling(Math.Sqrt(x)); for (int factor = 1; factor &lt; max; factor++) { if(x % factor == 0) { yield return factor; if(factor != max) yield return x / factor; } } } </code></pre> <p>In ticks. When factoring the number 20, 5 times each:</p> <ul> <li>GetFactors1-5,445,881</li> <li>GetFactors2-4,308,234</li> <li>GetFactors3-2,913,659 </li> </ul> <p>When factoring the number 20000, 5 times each:</p> <ul> <li>GetFactors1-5,644,457</li> <li>GetFactors2-12,117,938</li> <li>GetFactors3-3,108,182</li> </ul>
 

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