prime factors PAT-A1059

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.

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
题意:给出一个int 范围的整数,按照从到大的顺序输出其分解为质因数的乘法算式。

题目分析: 首先 2*3*5*7*11*13*17*19*23*29,最小的十个质因数相乘就已经超出了 int 的范围,所以 int 范围的整数最多可分解成十个不同的质因子。所以 fac 数组开到 10 就行。

    先把素数表打印出来,因为是 int 范围,所以素数表打印到 1e5 就行。

    注意:因为 1 不是素数,当 n==1 时,需要特判输出 "1=1".

代码如下:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn=1e5;
bool isprime[maxn];
int prime[maxn],nprime=0;
void doprime()///素数打表
{
    long long i,j;
    memset(isprime,true,sizeof(isprime));
    isprime[1]=false;
    for(i=2;i<=maxn;i++)
        if(isprime[i])
    {
        prime[++nprime]=i;
        for(j=i*i;j<=maxn;j+=i)
            isprime[j]=false;
    }
}
struct factor///结构体存放质因子及其个数
{
    int x;
    int cnt;
}fac[10];
int main()
{
    doprime();
    int n;
    int num=0;///n为不同的质因子的个数(质因子的数量)
    scanf("%d",&n);
    if(n==1) printf("1=1");
    else
    {
        printf("%d=",n);
        int sqr=(int)sqrt(double(n));
        for(int i=1;i<=nprime&&prime[i]<=sqr;i++)
            if(n%prime[i]==0)
        {
            fac[num].x=prime[i];
            fac[num].cnt=0;
            while(n%prime[i]==0)
            {
                fac[num].cnt++;
                n/=prime[i];
            }
            num++;///每存一个质因子,就加一
        }
        if(n!=1)
        {
            fac[num].x=n;
            fac[num].cnt=1;
            num++;
        }
        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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值