- 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:
- 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.
- 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).
- 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.
推薦閱讀
- HTML5+CSS3王者歸來
- MySQL數據庫基礎實例教程(微課版)
- jQuery Mobile移動應用開發實戰(第3版)
- TypeScript 2.x By Example
- Android系統下Java編程詳解
- 現代C:概念剖析和編程實踐
- Appcelerator Titanium:Patterns and Best Practices
- C#程序設計基礎入門教程
- C語言程序設計與應用實驗指導書(第2版)
- Responsive Web Design with jQuery
- 邊做邊學深度強化學習:PyTorch程序設計實踐
- Unity3D高級編程:主程手記
- 交互設計語言:與萬物對話的藝術(全兩冊)
- Java 開發從入門到精通
- Learn Spring for Android Application Development