码迷,mamicode.com
首页 > 其他好文 > 详细

PTA(Advanced Level)1059.Prime Factors

时间:2020-03-21 13:10:32      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:cas   file   level   osi   std   while   href   problems   质因数分解   

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

标签:cas   file   level   osi   std   while   href   problems   质因数分解   

原文地址:https://www.cnblogs.com/MartinLwx/p/12538484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!