1.题目要求求一个数的质因数分解。
2.一个大于等于2的数,质因数分解分两种情况:
1)如果这个数是质数,那么质因数分解就是它本身;
2)如果不是质数,那么除去最大的质因数后,剩下的质因数均小于sqrt(n),所以遍历到sqrt(n)即可。
3.注意输入为1的情况,输出应该为1=1。
时间限制
50 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
HE, Qinming
Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1* p2^k2 *…*pm^km.
Input Specification:
Each input file contains one test case which gives a positive integer N in the range of long int.
Output Specification:
Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi‘s are prime factors of N in increasing order, and the exponent ki is the number of pi — hence when there is only one pi, ki is 1 and must NOT be printed out.
Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
AC代码:
//#include<string> //#include<stack> //#include<unordered_set> //#include <sstream> //#include "func.h" //#include <list> #include <iomanip> #include<unordered_map> #include<set> #include<queue> #include<map> #include<vector> #include <algorithm> #include<stdio.h> #include<iostream> #include<string> #include<memory.h> #include<limits.h> #include<stack> using namespace std; int main(void) { int n; cin >> n; int outPur = n; vector<pair<int, int>> factor(0); int tmp = sqrt(n) + 1; for (int i = 2; i <= tmp; i++) {//遍历到sqrt(n)+1即可 if (n%i == 0) { factor.push_back({ i, 1 }); n /= i; while (n%i == 0) { factor.back().second++; n /= i; } } } if (n != 1)//如果最后不为1,那么这个是最大质因数 factor.push_back({ n, 1 }); if (outPur == 1) {//注意1的情况 printf("1=1\n"); return 0; } printf("%d=", outPur); for (int i = 0; i < factor.size(); i++) { printf("%d", factor[i].first); if (factor[i].second != 1) printf("^%d", factor[i].second); if (i != factor.size() - 1) printf("*"); } cout << endl; return 0; }