PTA(Advanced Level)1059.Prime Factors

Posted martinlwx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA(Advanced Level)1059.Prime Factors相关的知识,希望对你有一定的参考价值。

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1kp2k2×?×*pmk**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 = p1^k1*p2^k2**pm^km, where *p**i‘s are prime factors of N* in increasing order, and the exponent *k**i* 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
思路
  • 质因数分解和因数分解类似,只是要先得到质数表,我这里使用的是质数筛法
  • (N)的最大是(2^{31}-1)(sqrt{n}approx2^{15.5}),除非这个数本身是质数,不然我们因子判断到(sqrt{n})就好了
代码
#include<bits/stdc++.h>
using namespace std;
struct factor
{
    int x;  //质数
    int n;  //阶数
}fac[50];   
int primes[100100];
int prime_length = 0;
void gen_prime()
{
    int MAXN = 100100;
    bool flag[MAXN] = {0};
    for(int i=2;i<MAXN;i++)
    {
        if(!flag[i])
        {
            primes[prime_length++] = i;
            for(int j=i+i;j<MAXN;j+=i)  flag[j] = true;
        }
    }
}//质数筛法

int main()
{
    int n, n_copy;
    cin >> n;
    n_copy = n;
    gen_prime();

    int last_pos = 0;
    if(n == 1)  cout << "1=1";      //1是特殊情况
    else
    {
        int sqrt_value = (int)sqrt(n * 1.0);    //一个数的因子除了自身不会超过自身的根号n
        for(int i=0;primes[i]<sqrt_value && i<prime_length;i++)     //不超过根号n,以及不超过质数表的长度
        {
            while(n % primes[i] == 0)
            {
                fac[last_pos].x = primes[i];
                fac[last_pos].n == 0;
                while(n % primes[i] == 0)
                {
                    fac[last_pos].n++;
                    n /= primes[i];
                }
                last_pos++;
            }
            if(n == 1)  break;
        }

        if(n != 1)  //说明自己本身就是质数了
        {
            fac[last_pos].x = n;
            fac[last_pos].n = 1;
            last_pos++;
        }


        cout << n_copy << "=";
        for(int i=0;i<last_pos;i++)
        {
            if(fac[i].n != 1)
                printf("%d^%d", fac[i].x, fac[i].n);
            else
                printf("%d", fac[i].x);
            if(i != last_pos - 1)
                printf("*");
        }
    }
    return 0;
}
引用

https://pintia.cn/problem-sets/994805342720868352/problems/994805415005503488

以上是关于PTA(Advanced Level)1059.Prime Factors的主要内容,如果未能解决你的问题,请参考以下文章

PTA(Advanced Level)1025.PAT Ranking

PTA (Advanced Level)1022 Digital Library

PTA(Advanced Level)1059.Prime Factors

PTA(Advanced Level)1044.Shopping in Mars

PTA(Advanced Level)1036.Boys vs Girls

PTA (Advanced Level)1013 Battle Over Cities