Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1×p2k2×⋯×pmkm.
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
题意:
给出一个数,要求写出其质因子乘积的形式,相同的质因子用指数表示。
思路:
首先打出一个素数表,然后遍历素数表中的素数,如果该素数是所给数字的因子则记录下来,更新所给数字 temp /= i。如果最后temp > 1,则也要将其输出。
Code:
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 int main() { 6 long long n; 7 cin >> n; 8 if (n == 1) { 9 cout << n << "=" << n; 10 return 0; 11 } else { 12 cout << n << "="; 13 } 14 vector<int> prime(50005, 1); 15 prime[0] = prime[1] = 0; 16 for (int i = 2; i * i < 50000; ++i) { 17 for (int j = 2; i * j < 50000; ++j) { 18 prime[i * j] = 0; 19 } 20 } 21 bool isFirst = true; 22 int temp = n; 23 for (int i = 2; i < 50005; ++i) { 24 int cnt = 0; 25 bool found = false; 26 while (prime[i] == 1 && temp % i == 0) { 27 temp /= i; 28 cnt++; 29 found = true; 30 } 31 if (found) { 32 if (isFirst) { 33 cout << i; 34 if (cnt > 1) cout << "^" << cnt; 35 isFirst = false; 36 } else { 37 cout << "*" << i; 38 if (cnt > 1) cout << "^" << cnt; 39 } 40 } 41 } 42 if (temp > 1) cout << (isFirst ? "" : "*") << temp << endl; 43 return 0; 44 }