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

  • The Modern C++ Challenge
  • Marius Bancila
  • 285字
  • 2021-06-25 22:01:24

9. Prime factors of a number

The prime factors of a positive integer are the prime numbers that pide that integer exactly. For instance, the prime factors of 8 are 2 x 2 x 2, and the prime factors of 42 are 2 x 3 x 7. To determine the prime factors you should use the following algorithm:

  1. While n is pisible by 2, 2 is a prime factor and must be added to the list, while n becomes the result of n/2. After completing this step, n is an odd number.
  2. Iterate from 3 to the square root of n. While the current number, let’s call it i, pides n, i is a prime factor and must be added to the list, while n becomes the result of n/i. When i no longer pides n, increment i by 2 (to get the next odd number).
  3. When n is a prime number greater than 2, the steps above will not result in n becoming 1. Therefore, if at the end of step 2 n is still greater than 2, then n is a prime factor.
std::vector<unsigned long long> prime_factors(unsigned long long n)
{
std::vector<unsigned long long> factors;
while (n % 2 == 0) {
factors.push_back(2);
n = n / 2;
}
for (unsigned long long i = 3; i <= std::sqrt(n); i += 2)
{
while (n%i == 0) {
factors.push_back(i);
n = n / i;
}
}

if (n > 2)
factors.push_back(n);
return factors;
}

int main()
{
unsigned long long number = 0;
std::cout << "number:";
std::cin >> number;
   auto factors = prime_factors(number);
std::copy(std::begin(factors), std::end(factors),
std::ostream_iterator<unsigned long long>(std::cout, " "));
}

As a further exercise, determine the largest prime factor for the number 600,851,475,143.

主站蜘蛛池模板: 安阳市| 富蕴县| 淮阳县| 肥西县| 冀州市| 桦南县| 讷河市| 清水县| 郑州市| 霸州市| 松潘县| 大石桥市| 扎赉特旗| 黎平县| 会同县| 东乌珠穆沁旗| 通河县| 岳池县| 襄垣县| 松溪县| 韶关市| 镶黄旗| 黄石市| 白城市| 通化市| 黑河市| 独山县| 东丽区| 昌吉市| 青龙| 涟水县| 扎赉特旗| 嘉峪关市| 舟曲县| 廉江市| 浦城县| 黄浦区| 涡阳县| 利津县| 丹东市| 旌德县|