Note that there are some explanatory texts on larger screens.

plurals
  1. POPossible optimization in my code?
    primarykey
    data
    text
    <p>In order to solve the <a href="http://projecteuler.net/problem=5" rel="nofollow">Euler Project problem n°5</a>, I wrote the following program:</p> <pre><code>class p5 { const int maxNumber = 20; static void Main(string[] args) { Job(); // First warm-up call to avoid Jit latency var sw = Stopwatch.StartNew(); var result = Job(); sw.Stop(); Debug.Assert(result == 232792560); Console.WriteLine(result); Console.WriteLine(sw.Elapsed); Console.ReadLine(); } private static int Job() { var result = Enumerable.Range(1, int.MaxValue - 1) .Where( n =&gt; Enumerable.Range(maxNumber / 2 + 1, maxNumber / 2).All(c =&gt; n % c == 0) ).First(); return result; } } </code></pre> <p>However, I found this is a bit long (17 seconds, in release mode), even if it's working.</p> <p>Is there any possible optimization ?</p> <p>FYI, I tried with <code>AsParallel</code> method, but as expected, the chunk of works are too small and the context switch was heavier than the benefits (more that 1 minute) :</p> <pre><code> var result = Enumerable.Range(1, int.MaxValue - 1).AsParallel() .Where( n =&gt; Enumerable.Range(maxNumber / 2 + 1, maxNumber / 2).All(c =&gt; n % c == 0) ).First(); return result; </code></pre> <p>[Edit] According martin's suggestion, this version divided by 10 the time taken :</p> <pre><code> private static int Job() { var n =2; bool result; do { result = true; for (int c = maxNumber / 2; c &lt;= maxNumber; c++) { if (n % c &gt; 0) { result = false; break; } } n ++;//= 2; } while (!result); return n; } </code></pre> <p><strong>[Edit]</strong> To sum up all my tests, rough execution time :</p> <ul> <li>My first implementation : 20 secs</li> <li>Removed the inner enumerable.Range call (replaced by a simple for loop): 3 seconds</li> <li>Removed the outer and inner enumerable.Range call: 1.5 second</li> <li>Only taking even numbers : (with loops only, no enumerable.range) : less than 1 second</li> <li>Using Gcd/LCm euclidean algorithms as suggested by drhirsch : 0.004 ms</li> </ul> <p>The latest suggestion is clearly the good answer. I thank drhirsch for suggesting another approach instead of only simple loop optimization</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.
 

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