1059 Prime Factors (25point(s)) - PAT 甲级 C语言

1059 Prime Factors (25point(s))

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1 × p2k2 x … x pmkm.

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 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^211171011291

题目大意:

给一个整数 N,从小到大输出该数的质因子

设计思路:

建立一个素数表,遍历素数表,查找质因子

  • INT 最大值为 2147483647,开根号得 46340.95,素数表大小 5 万左右
  • 所以不能被 5 万以内整除的数一定是素数
  • 当最后 N > 1 时,state 是为了标示是否输出过因子,例如 30027 = 3 * 10009,最后输出 10009 前面要有 * 号
编译器:C (gcc)
#include<stdio.h>

#define MAX 46342
//INT 2147483647 46340.95
int main(void) {
        int prime[MAX] = {-1, -1};
        int i, j;
        for (i = 2; i * i < MAX; i++) {
                for (j = 2; i * j < MAX; j++) {
                        prime[i * j] = -1;
                }
        }

        int n;
        scanf("%d", &n);
        printf("%d=", n);
        if (n == 1) {
                printf("1");
        }
        int state = 0;
        for (i = 2; i < MAX && n >= 2; i++) {
                int count = 0, flag = 0;
                while (prime[i] == 0 && n % i == 0) {
                        count++;
                        n /= i;
                        flag = 1;
                }
                if (flag) {
                        if (state) {
                                printf("*");
                        }
                        printf("%d", i);
                        state = 1;
                }
                if (count > 1) {
                        printf("^%d", count);
                }
        }
        if (n > 1) {
                printf("%s%d", state ? "*": "", n);
        }

        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值