1059. Prime Factors (25)

本文提供了一道 PAT A 类题目 (编号 1059) 的详细解答过程,该题要求对输入的每个整数进行质因数分解并按指定格式输出。解答中使用了 C++ 语言实现,包括判断质数的函数和质因数分解的逻辑。

题目地址:http://www.patest.cn/contests/pat-a-practise/1059

#include <cstdio>  
#include <iostream> 
#include <vector>  
#include <set>
#include <algorithm>
#include <stack>
using namespace std;

bool isPrime(long int n)
{
    if(n == 1)
        return false;
    if(n == 2)
        return true;
    long int i ;
    for( i = 2 ;i*i <= n ; i++)
    {
        if( n % i == 0)
            return false;
    }
    return true;
}

long int primes[3000];

struct data{
    long int factor ;
    int fcount ;
};
vector<data> vans ;

int main()
{
    //freopen("in.txt", "r", stdin);

    long int tmp = 3;
    primes[0] = 2 ;
    int num = 1 ;
    while(tmp < 5000)
    {
        if(isPrime(tmp))
            primes[num++] = tmp;
        tmp += 2 ;
    }

    while(scanf("%d",&tmp) != EOF)
    {
        if(isPrime(tmp) || tmp == 1)
            printf("%ld=%ld\n",tmp,tmp);
        else{
            printf("%ld=",tmp);
            vans.clear();
            num = 0;
            while( !isPrime(tmp) )
            {
                while( tmp % primes[num] != 0)
                {
                    num ++ ;
                }
                data dt ;
                dt.factor = primes[num];
                int count = 0;
                while(tmp % dt.factor == 0)
                {
                    count ++ ;
                    tmp /= dt.factor;
                }
                dt.fcount = count ;
                vans.push_back(dt);
                num = num + 1 ;

                if( isPrime(tmp)){
                    dt.factor = tmp ;
                    dt.fcount = 1;
                    vans.push_back(dt);
                    break;
                }
                if(tmp == 1)
                    break;
            }

            printf("%d",vans[0].factor);
            if(vans[0].fcount != 1)
            {
                printf("^%d",vans[0].fcount);
            }
            int len = vans.size();
            for(int j = 1 ; j < len ; j++)
            {
                printf("*%d",vans[j].factor);
                if(vans[j].fcount != 1)
                {
                    printf("^%d",vans[j].fcount);
                }
            }
            printf("\n");
        }//else
    } // while

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值