1059. Prime Factors (25)
2016-02-15 15:13
701 查看
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:
Sample Output:
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
#include <iostream> #include <vector> #include <cmath> #include <cstddef> #include <map> using namespace std; long int next_prime(int n) { for (int i = n+1;; i++) { bool is_prime = true; for (int j = 2; j <= sqrt(i); j++) { if (i%j == 0) { is_prime = false; break; } } if (is_prime == true) { return i; } } } int main() { map<int,int> primes; long int n; long int prime = 2; cin >> n; if (n == 1) { printf("1=1"); return 0; } long output = n; while (prime <= n ) { if (n % prime == 0) { primes[prime]++; n /= prime; } else { prime = next_prime(prime); } } cout << output << "="; bool first = true; for (auto itr = primes.begin(); itr != primes.end(); ++itr) { if (first == true) { first = false; if (itr->second > 1) { printf("%d^%d", itr->first, itr->second); } else { printf("%d", itr->first); } } else { if (itr->second > 1) { printf("*%d^%d", itr->first, itr->second); } else { printf("*%d", itr->first); } } } return 0; }
相关文章推荐
- libdvbpsi源码分析(四)PAT表解析/重建
- PAT配置
- 什么是端口复用动态地址转换(PAT) 介绍配置实例
- MikroTik layer7-protocol
- PAT是如何工作的
- PAT 乙级题:1002. 写出这个数 (20)
- PAT (Advanced Level) Practise 1001-1010
- 数据结构学习与实验指导(一)
- PAT Basic Level 1001-1010解题报告
- 1001. 害死人不偿命的(3n+1)猜想
- 1002. 写出这个数
- 1032. 挖掘机技术哪家强
- 1001. 害死人不偿命的(3n+1)猜想 (PAT basic)
- 1002. 写出这个数(PAT Basic)
- 1004. 成绩排名(PAT Basic)
- 1006. 换个格式输出整数(PAT Basic)
- 1007. 素数对猜想(PAT Basic)
- 1008. 数组元素循环右移问题
- 1009. 说反话(PAT Basic)
- 1011. A+B和C(PAT Basic)