PAT A1059

!:质因子分解,面向题目的话很多特殊情况没有考虑,仅作为暑假写题记录思路

#include<iostream>
#include<stdlib.h>
#include<cmath>

using namespace std;

const int maxn = 1e5 + 10;   //求maxn内的质数,由要分解的数为int确定;

int prime[maxn], pri_n = 0;

struct factor
{
    int x;
    int cnt;
}fac[10];

bool IsPrime(int a)
{
    for(int i = 2; i <= sqrt(a); i++)
    {
        if(a % i == 0) return false;
    }

    return true;
}

void FindPrime()
{
    for(int i = 2; i <= maxn; i++)
    {
        if(IsPrime(i))  prime[ pri_n++ ] = i;
    }
}

int main()
{
    FindPrime();  //求2~maxn素数表;

    int n;
    cin >> n;

    cout << n << "=";


/// 进行分解;
    int num = 0; // n的不等质因子个数
    for(int i = 0; prime[i] <= sqrt(n) ; 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) break;
    }

    if(n != 1)
    {
        fac[num].x = n;
        fac[num].cnt = 1;
        num ++;
    }


/ 进行输出
    cout << fac[0].x;
    if(fac[0].cnt != 0) cout << "^" << fac[0].cnt;

    for(int i = 1; i < num; i++)
    {
        cout << "*" << fac[i].x;
        if(fac[i].cnt != 1)
            cout << "^" << fac[i].cnt;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值