Problem 3:Largest prime factor
标签:质因数分解
原文:The prime factors of 13195 13195 13195 are 5 5 5, 7 7 7, 13 13 13 and 29 29 29.
What is the largest prime factor of the number 600851475143 600851475143 600851475143?
翻译: 13195 13195 13195 的质因数包括 5 5 5、 7 7 7、 13 13 13和 29 29 29。
600851475143 600851475143 600851475143 的最大质因数是多少?
题解:直接质因数分解进行求解即可,时间复杂度为 O ( n ) O(\sqrt n) O(n)
算法流程:扫描 2 − n 2−\sqrt n 2−n 的每个数 x x x,若 x x x 能整除 n n n,则从 n n n 中除掉所有质因子 x x x。
上述算法 保证一个合数的因子一定在扫描到这个合数之前除掉了,所以这个过程中所得到的能整除 n n n 的一定是质数。时间复杂度为 O ( n ) O(\sqrt n) O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
ll n = 600851475143, mx = 0;
for (ll i = 2; i <= sqrt(n); i++) {
while (n % i == 0) {
n /= i;
mx = max(mx, i);
}
}
if (n > 1) mx = max(mx, n);
cout << n << endl;
return 0;
}
“Project Euler exists to encourage, challenge, and develop the skills and enjoyment of anyone with an interest in the fascinating world of mathematics.”
“欧拉计划的存在,是为了每个对数学感兴趣的人,鼓励他们,挑战他们,并最终培养他们的能力与乐趣。”