Note that there are some explanatory texts on larger screens.

plurals
  1. POParallel.For in C#
    text
    copied!<p>I am trying convert the following Collatz Conjecture algorithm from:</p> <pre><code> public class CollatzConjexture { public static int Calculate(int StartIndex, int MaxSequence) { int ChainLength = 0; int key = 0; bool ContinuteCalulating = true; int LongestChain = 0; Int64 Remainder = 0; for (int i = StartIndex; i &lt;= MaxSequence; i++) { ChainLength = 1; Remainder = i; ContinuteCalulating = true; while (ContinuteCalulating) { Remainder = CalculateCollatzConjecture(Remainder); if (Remainder == 1) ContinuteCalulating = false; ChainLength += 1; } if (ChainLength &gt; LongestChain) { LongestChain = ChainLength; key = i; } } return key; } private static Int64 CalculateCollatzConjecture(Int64 Number) { if (Number % 2 == 0) return Number / 2; else return (3 * Number) + 1; } } </code></pre> <p>To instead use the .NET 4.0 Parallel.For :</p> <pre><code>int ChainLength = 0; int key = 0; bool ContinuteCalulating = true; int LongestChain = 0; Int64 Remainder = 0; int[] nums = Enumerable.Range(1, 1500000).ToArray(); long total = 0; // Use type parameter to make subtotal a long, not an int Parallel.For&lt;int&gt;(1, nums.Length, () =&gt; 1, (j, loop, subtotal) =&gt; { Remainder = j; while (ContinuteCalulating) { Remainder = CalculateCollatzConjecture(Remainder); if (Remainder == 1) ContinuteCalulating = false; ChainLength += 1; } if (ChainLength &gt; LongestChain) { LongestChain = ChainLength; key = j; } return key; }, (x) =&gt; Interlocked.Add(ref key, x) ); </code></pre> <p>I have a feeling I'm not too far from it, famous last words.</p> <p>Thanks in advance.</p>
 

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