Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your problem is that you don't want to use <code>Parallel.For</code> in this instance because you already have an array (<code>nums</code>) to iterate over, which calls for <code>Parallel.ForEach</code>. However, your array is created with <code>Enumerable.Range</code> and you don't actually use it for anything, so the best way to do it is with <code>AsParallel</code> and LINQ (PLINQ):</p> <pre><code>public static class CollatzConjexture2 { public static int Calculate(int StartIndex, int MaxSequence) { var nums = Enumerable.Range(StartIndex, MaxSequence); return nums.AsParallel() // compute length of chain for each number .Select(n =&gt; new { key = n, len = CollatzChainLength(n) }) // find longest chain .Aggregate((max, cur) =&gt; cur.len &gt; max.len || // make sure we have lowest key for longest chain max.len == cur.len &amp;&amp; cur.key &lt; max.key ? cur : max) // get number that produced longest chain .key; } private static int CollatzChainLength(Int64 Number) { int chainLength; for (chainLength = 1; Number != 1; chainLength++) Number = (Number &amp; 1) == 0 ? Number &gt;&gt; 1 : Number * 3 + 1; return chainLength; } } </code></pre> <p>This method is about twice as fast on my computer as the serial implementation. Also note that I optimized the main loop so that it does the computation inline rather than calling a function and it uses bitwise math instead of multiplying and dividing. This made it about twice as fast again. Compiling it for x64 instead of x86 also made it more than twice as fast.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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