PATA 1059 Prime Factors

题目:

Given any positive integer N N N, you are supposed to find all of its prime factors, and write them in the format N = p 1 p_1 p1^ ​ k 1 ​k_1 k1× p ​ 2 p_​2 p2^ k ​ 2 k_​2 k2×⋯× p ​ m p​_m pm^ ​ k m ​k_m 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 = p ​ 1 p_​1 p1^ k 1 k_1 k1* p 2 p_2 p2^ k 2 k_2 k2 p m p_m pm^ k m k_m km , where p ​ i p_​i pi's are prime factors of N N N in increasing order, and the exponent k ​ i k_​i ki is the number of p ​ i p_​i pi – hence when there is only one p i ​ p_i​ pi , k ​ i k_​i ki is 1 1 1 and must NOT be printed out.

Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291

注意点:
  1. N=1时需要单独处理输出“1=1”。
  2. 因为最多只会有一个大于sqrt(N)的质因数,因为N在int范围内(int 又称 long int)所以素数表开到 1 0 5 10^5 105 即可。
  3. 输出时需要小心。
代码:
#include <stdio.h>
#include <math.h>

const int MAX_N=100010;

//质因数结构
struct prime_factor{
    int factor;
    int pow=0;
};

int N;
bool find_prime[MAX_N]={false};
int prime[MAX_N];
prime_factor factors[MAX_N];

//计算范围n以内的素数表
int gen_prime(int n){
    int num_prime=0;
    for(int i=2;i<=n;i++){
        if(find_prime[i]==false){
            prime[num_prime++]=i;
            for(int j=i+i;j<=n;j+=i)
                find_prime[j]=true;
        }
    }
    return num_prime;//返回生成的素数表长度
}

int main(){
    scanf("%d",&N);
    int s=sqrt(1.0*N);
    int num_prime= gen_prime(s);
    int index=-1,cnt=0;
    printf("%d=",N);
    //单独判断N==1的情况,否则不会有结果输出
    if(N==1){
        printf("1\n");
        return 0;
    }
    //计算质因数
    for(int i=0;i<num_prime;i++){
        if(N%prime[i]==0){
            index++;
            cnt++;
        }
        while(N%prime[i]==0){
            factors[index].factor=prime[i];
            factors[index].pow++;
            N/=prime[i];
        }
    }
    //按照格式输出结果
    for(int i=0;i<cnt;i++){
        if(i<1) printf("%d",factors[i].factor);
        else printf("*%d",factors[i].factor);
        if(factors[i].pow!=1) printf("^%d",factors[i].pow);
    }
    if(N!=1){
        if(cnt>0) printf("*%d\n",N);
        else  printf("%d\n",N);
    }
    else printf("\n");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值