文章目录
- 1 题目
- 2 解析
- 2.1 题意
- 2.2 思路
- 3 参考代码
1 题目
1059 Prime Factors (25分)
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
2 解析
2.1 题意
求给出数的质因子乘积(从小到大)
2.2 思路
先把素数表打印出来,然后再进行质因子分解操作。
- 对n==1,进行特判输出“1=1”;
- 对于int范围的正整数进行质因子分解,素数表开到105大小就可以了。
3 参考代码
#include
#include
const int MAXN = 100000;
struct factor
{
int x;
int cnt;
}fac[10];
bool p[MAXN] = {false};
int prime[MAXN], pNum = 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[i] = true;
}
}
}
}
void find_factor(int n, int &count){
int sqr =(int)sqrt(1.0*n);
for (int i = 0; i < MAXN && i <= sqr; ++i)
{
if(n % prime[i] == 0){
fac[count].x = prime[i];
fac[count].cnt = 0;
while(n % prime[i] == 0){
fac[count].cnt++;
n/=prime[i];
}
count++;
}
}
if(n != 1){
fac[count].x = n;
fac[count++].cnt = 1;
}
}
int main(int argc, char const *argv[])
{
find_Prime();
int n, num = 0;
scanf("%d", &n);
if(n == 1){
printf("1=1");
}else{
find_factor(n, num);
printf("%d=", n);
for (int i = 0; i < num; ++i)
{
if(i != 0) printf("*");
printf("%d", fac[i].x);
if(fac[i].cnt > 1){
printf("^%d", fac[i].cnt);
}
}
}
return 0;
}