看《单墫老师教你学数学》了解了一个很巧妙的质因数分解的算法,C++代码如下:
/*
* 求正整数n的最小质因数
*/
uint64_t FactorDecomposer::minimalPrimeFactor(uint64_t n) {
if ( n % 2 == 0 ) return 2;
uint64_t M = n, N = n, b = 3, r = 0;
while ( ( r = N%b ) != 0 ) {
uint64_t q = N/b;
M = M - 2*q;
N = M + r;
b+=2;
}
return b;
}
/*
* 质因数分解
*/
void FactorDecomposer::decomposePrimeFactor(uint64_t n) {
uint64_t k = n, x;
do {
x = minimalPrimeFactor(k);
std::cout << x << " ";
k = k / x;
} while ( k != 1 );
}