Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the best way to get all the divisors of a number?
    primarykey
    data
    text
    <p>Here's the very dumb way:</p> <pre><code>def divisorGenerator(n): for i in xrange(1,n/2+1): if n%i == 0: yield i yield n </code></pre> <p>The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)</p> <p>I can find prime factors and their multiplicity fast enough. I've an generator that generates factor in this way:</p> <p>(factor1, multiplicity1)<br> (factor2, multiplicity2)<br> (factor3, multiplicity3)<br> and so on...</p> <p>i.e. the output of </p> <pre><code>for i in factorGenerator(100): print i </code></pre> <p>is:</p> <pre><code>(2, 2) (5, 2) </code></pre> <p>I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make</p> <pre><code>for i in divisorGen(100): print i </code></pre> <p>output this:</p> <pre><code>1 2 4 5 10 20 25 50 100 </code></pre> <hr> <p><strong>UPDATE:</strong> Many thanks to Greg Hewgill and his "smart way" :) Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D</p> <p><strong>UPDATE 2:</strong> Stop saying this is a duplicate of <a href="https://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number">this</a> post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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