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

14. Unique prime factors

One obvious way to find a number's unique prime factors is to find all of its prime factors and then remove duplicates. That would be relatively straightforward and fast.

An alternative strategy would be to modify the code that factors numbers so that it only saves one copy of each prime factor. The following method takes this approach:

// Find a number's unique prime factors.
private List<long> FindUniquePrimeFactors(long number)
{
checked
{
List<long> factors = new List<long>();

// Pull out 2s.
if (number % 2 == 0)
{
factors.Add(2);
while (number % 2 == 0) number /= 2;
}

// Pull out odd factors.
long limit = (long)Math.Sqrt(number);
for (long factor = 3; factor <= limit; factor += 2)
{
if (number % factor == 0)
{
factors.Add(factor);
while (number % factor == 0)
{
number /= factor;
limit = (long)Math.Sqrt(number);
}
}
}

// Add the leftover.
if (number != 1) factors.Add(number);
return factors;
}
}

This method is similar to the one used in the preceding solution, except it only keeps one copy of each prime factor.

Like the preceding solution, you can make this solution faster if you build a prefilled list of prime numbers to use when searching for factors.

The lesson to be learned here is that you can sometimes solve a new problem by reusing an existing solution, but sometimes it's worth modifying the existing solution to make the new approach simpler.

Download the UniquePrimeFactors example solution to see additional details.

主站蜘蛛池模板: 丰都县| 苍山县| 周口市| 中西区| 通辽市| 临邑县| 奉节县| 闵行区| 枣强县| 聂拉木县| 罗平县| 杭州市| 南投市| 淮阳县| 旅游| 宁夏| 包头市| 双流县| 邮箱| 弋阳县| 久治县| 凤阳县| 克什克腾旗| 遂昌县| 洪雅县| 房产| 龙海市| 修文县| 鄂伦春自治旗| 蒙山县| 海晏县| 东辽县| 洛阳市| 云浮市| 拉孜县| 敦煌市| 二手房| 双辽市| 宁晋县| 资源县| 遂宁市|