Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>My answer here isn't pretty or elegant, it is still brute force. But, it simplifies the problem space a little and terminates successfully in less than 10 seconds.</p> <p><strong>Getting factors of n:</strong> Like @usethedeathstar mentioned, it is possible to test for factors only up to <code>n/2</code>. However, we can do better by testing only up to the square root of n:</p> <pre><code>let n = 36 =&gt; factors(n) : (1x36, 2x18, 3x12, 4x9, 6x6, 9x4, 12x3, 18x2, 36x1) </code></pre> <p>As you can see, it loops around after 6 (the square root of 36). We also don't need to explicitly return the factors, just find out how many there are... so just count them off with a generator inside of sum():</p> <pre><code>import math def get_factors(n): return sum(2 for i in range(1, round(math.sqrt(n)+1)) if not n % i) </code></pre> <p><strong>Testing the triangular numbers</strong></p> <p>I have used a generator function to yield the triangular numbers:</p> <pre><code>def generate_triangles(limit): l = 1 while l &lt;= limit: yield sum(range(l + 1)) l += 1 </code></pre> <p>And finally, start testing:</p> <pre><code>def test_triangles(): triangles = generate_triangles(100000) for i in triangles: if get_factors(i) &gt; 499: return i </code></pre> <p>Running this with the profiler, it completes in less than 10 seconds:</p> <pre><code>$ python3 -m cProfile euler12.py 361986 function calls in 8.006 seconds </code></pre> <p>The BIGGEST time saving here is <code>get_factors(n)</code> testing only up to the square root of n - this makes it heeeaps quicker and you save heaps of memory overhead by not generating a list of factors.</p> <p>As I said, it still isn't pretty - I am sure there are more elegant solutions. But, it fits the bill of being faster :)</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.
 

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