/* 寻找所有因数 包括1和其本身*/
std::vector<int>factorize(int n){std::vector<int> answer;int k =(int)sqrt((double)n);int i =0;for(i =1; i <= k; i++){if(!(n%i)){answer.push_back(i);answer.push_back(n / i);}}sort(answer.begin(), answer.end());// 利用sort函数进行排序,再输出,这一步若不是必须可省略std::cout <<" The factors of "<< n <<" are";return answer;}/* 打印vector */voidprint_vector(std::vector<int>& vec){for(auto it = vec.cbegin(); it != vec.cend();++it)std::cout <<' '<<*it;std::cout <<'\n';}voidtest_factorize(){std::vector<int> vf;vf =factorize(2);print_vector(vf);vf =factorize(72);print_vector(vf);vf =factorize(196);print_vector(vf);}
质因数分解
/* 质因数分解 */
std::vector<int>prime_factorize(int n){std::vector<int> answer;if(n !=2){int k =(int)sqrt((double)n);// 只需要循环到 √n 即可int i =0, m = n;for(i =2; i <= k; i++){while(m%i ==0){m = m / i;answer.push_back(i);}if(m == n)answer.push_back(n);}}elseanswer.push_back(n);std::cout <<" The prime factorization of "<< n <<" are";return answer;}voidtest_prime_factorize(){std::vector<int> vf;vf =prime_factorize(2);print_vector(vf);vf =prime_factorize(72);print_vector(vf);vf =prime_factorize(196);print_vector(vf);}intmain(){test_isprime();test_factorize();test_prime_factorize();return0;}