[Function] Check For Prime - C# Source - Printable Version +- Support Forums (https://www.supportforums.net) +-- Forum: Categories (https://www.supportforums.net/forumdisplay.php?fid=87) +--- Forum: Coding Support Forums (https://www.supportforums.net/forumdisplay.php?fid=18) +---- Forum: Visual Basic and the .NET Framework (https://www.supportforums.net/forumdisplay.php?fid=19) +---- Thread: [Function] Check For Prime - C# Source (/showthread.php?tid=25824) |
[Function] Check For Prime - C# Source - AceInfinity - 03-31-2012 I don't see too much C# stuff here, even though all I mainly do is VB.net and once in a while some C++. But here's a function I created in C# to check whether a number is prime or not, given a returned boolean value. I'll post the usage as well so you can try it out. To see, you can change around the variable of x which is just a type Int32. Code: private void button1_Click(object sender, EventArgs e) Nice efficient way of checking for primes I think I posted a VB.net version of this as well. But basically the way it works is it does a few firsthand checks; the only prime number divisible by 2 is 2. 0 and 1 are special numbers, NOT prime numbers. If we know a prime number other than 2 cannot be divisible evenly by 2 then we can skip all even numbers from 3 and up. So in our loop, we can utilize n to check each odd number from 3 forward by adding 2 each time. Lastly, we only need to go just before the halfway point, as any further and we'll basically be checking the multiples in reverse. Example: 3 * 7 If we know 21 is divisible by 3, which is 7, then we don't need to continue our loop to 7 since we know it's divisible by a factor of 3... Bad example, as 7 is not the halfway point for 21, but you can see the strategy in not having to go anywhere past the halfway point as we'll start running into the opposite multiples by that point undoubtedly. |