1059 Prime Factors (25分)

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 = p​1​k​1​​ ×p​2​k2​​ ×⋯×p​m​k​m​​ .

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 = p​1 ^k1​​ *p​2​​ ^k​2​​ *…*p​m​​ ^k​m​​ , where p​i
​​ 's are prime factors of N in increasing order, and the exponent k​i​​ is the number of p​i​​ – hence when there is only one p​i​​ , k​i​​ 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 <cstdio>
#include <cmath>

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;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页