官术网_书友最值得收藏!

11. Primality testing

One simple way to determine whether a number N is prime is to loop through all of the integers between 2 and N – 1 and use the modulus operator % to see if any of them divide the number evenly. There are a couple of ways that you can improve this approach.

First, note that once you check a potential divisor, you don't need to check any multiples of that divisor. For example, if 2 doesn't divide evenly into N, then 4, 6, 8, and other multiples of 2 also cannot divide evenly into N. To make the basic approach faster, you can test the divisor 2 separately and then make the loop consider only odd numbers.

You can also improve this method by changing the loop's upper limit. The original method considers values between 2 and N – 1, but you can change the upper limit to . To see why that works, suppose N has a factor A where A > , so the loop won't find A. In that case, N = A × B for some value, B. If A > , then B must be less than , so the loop won't find A, but it will find B.

Making the loop consider only odd numbers and making the loop end at  gives the following method for determining whether a number is prime:

// Return true if the number is prime.
private bool IsPrime(long number)
{
// Handle 2 separately.
if (number == 2) return true;
if (number % 2 == 0) return false;

// See if the number is divisible by odd values up to Sqrt(number).
long sqrt = (long)Math.Sqrt(number);
for (long i = 3; i <= sqrt; i += 2)
if (number % i == 0) return false;

// If we get here, the number is prime.
return true;
}

Note that this method only uses numbers that are smaller than N, so it cannot cause an integer overflow.

Download the PrimalityTesting example solution to see additional details.

主站蜘蛛池模板: 临泽县| 泰兴市| 凤翔县| 独山县| 临朐县| 潼南县| 搜索| 大英县| 巨鹿县| 南汇区| 洞口县| 岱山县| 始兴县| 德保县| 奎屯市| 集贤县| 肥东县| 阜城县| 武义县| 富阳市| 汝南县| 四川省| 长沙市| 罗田县| 武清区| 西城区| 册亨县| 堆龙德庆县| 合川市| 禹州市| 东台市| 兰西县| 兴城市| 富蕴县| 津市市| 柞水县| 平果县| 分宜县| 怀柔区| 乌鲁木齐县| 竹溪县|