题意
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
输入格式
Each input file contains one test case which gives a positive integer N in the range of long int.
输出格式
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.
输入样例
97532468
输出样例
97532468=2^2*11*17*101*1291
思路
常规质因数分解题型
代码
/**
* @tag PAT_A_
* @authors R11happy (xushuai100@126.com)
* @date 2016-9-11 3:30-3:54
* @version 1.0
* @Language C++
* @Ranking 540/1934
* @function null
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 100010;
int prime[maxn], pNum;
bool p[maxn] = { 0 };
void Find_Prime()
{
for (int i = 2; i < maxn; i++)
{
if (p[i] == false)
{
prime[pNum++] = i;
for (int j = i + i; j < maxn; j += i)
{
p[j] = true;
}
}
}
}
struct factor
{
long long x;
int cnt = 0;
}fac[10];
int main()
{
long long N;
int num = 0;
scanf("%lld", &N);
Find_Prime();
if (N == 1) printf("1=1"); //注意特判
else
{
printf("%lld=",N);
int sqr = (int)sqrt(1.0*N);
for (int i = 0; i < pNum && prime[i] <= sqr; i++)
{
if (N % prime[i] == 0)
{
fac[num].x = prime[i];
while (N % prime[i] == 0)
{
fac[num].cnt++;
N /= prime[i];
}
num++;
}
if (N == 1) break;
}
if (N != 1)
{
fac[num].x = N;
fac[num++].cnt++; //不是fac[num].cnt++
}
}
for (int i = 0; i < num; i++)
{
if (i > 0) printf("*");
printf("%lld", fac[i].x);
if (fac[i].cnt > 1) printf("^%d", fac[i].cnt);
}
return 0;
}
收获
- 打表
bool p[maxn] = { 1,1 };
void Find_Prime()
{
for (int i = 2; i < maxn; i++)
{
if (p[i] == false)
{
prime[pNum++] = i;
for (int j = i + i; j < maxn; j += i)
{
p[j] = true;
}
}
}
}
2.质因子结构
struct factor
{
long long x;
int cnt = 0;
}fac[10];
3.转成质因子相乘模板
if (N == 1) printf("1=1"); //注意特判
else
{
printf("%lld=",N);
int sqr = (int)sqrt(1.0*N);
for (int i = 0; i < pNum && prime[i] <= sqr; i++)
{
if (N % prime[i] == 0)
{
fac[num].x = prime[i];
while (N % prime[i] == 0)
{
fac[num].cnt++;
N /= prime[i];
}
num++;
}
if (N == 1) break;
}
if (N != 1) //如果无法被根号n以内的质因子除尽
{
fac[num].x = N; //那么一定有一个大于根号n的质因子
fac[num++].cnt++; //不是fac[num].cnt++
}
}