Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes there is. For one, you could check for 2 separately and then loop through only odd numbers. That would cut the search loop in half. There could be more elaborate things to do but basically that should answer your question.</p> <p><strong>UPDATED WITH CODE:</strong></p> <pre><code> public static bool IsPrime(int number) { if (number &lt; 2) return false; if (number % 2 == 0) return (number == 2); int root = (int)Math.Sqrt((double)number); for (int i = 3; i &lt;= root; i += 2) { if (number % i == 0) return false; } return true; } </code></pre> <p>There are many duplicate discussions on SO and plenty of links about various primality search methods. However, since the OP here has a method to check a <strong>signed 32-bit integer</strong>, and not something much larger like an unsigned 64-bit integer, then a quick check shows the truncated square root of int.MaxValue to be 46340. Since we are looping through only odd numbers that would result in a maximum loop of 23170 iterations, which in my opinion is quite fast as long as we are limiting the discussion to Int32. If the question revolved around UInt64, then other methods should maybe be investigated regarding faster.</p> <p>The code above takes care of <em>any</em> int value, not just the special case of 1. Perhaps you have a NumericUpDown control that limits the inputs but I don't know that from just the function shown. One could argue that it would be more proper to throw an exception if the input number is &lt; 2, but I skipped that '<em>feature</em>' here.</p> <p><strong>All</strong> even numbers are checked before the main loop, not just 2 (a common mistake).</p> <p>And while this could be homework (in July!!!), there are tons of links throughout the Internet that would have similar code so I am not doing someone's homework for them. Since my code was added days after the original post, the OP has had time to research and learn since then.</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.
    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