1059 Prime Factors (25 分)

本文介绍了一种用于将任意正整数N分解为其所有质因数的算法,并以递归方式展示质因数及其指数的输出。通过实例演示了如何使用C++实现这一算法。

 

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p​1​​​k​1​​​​×p​2​​​k​2​​​​×⋯×p​m​​​k​m​​​​.

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​​^k​1​​*p​2​​^k​2​​**p​m​​^k​m​​, 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^2*11*17*101*1291

C++:

/*
 @Date    : 2018-02-01 19:40:32
 @Author  : 酸饺子 (changzheng300@foxmail.com)
 @Link    : https://github.com/SourDumplings
 @Version : $Id$
*/

/*
https://www.patest.cn/contests/pat-a-practise/1059
 */

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

vector<long long> primeNum = {2};
int output = 0;
int k = 0;

bool isPrime(long long num)
{
    auto it = primeNum.begin();
    for (; it != primeNum.end(); ++it)
    {
        if (num % *it == 0)
            return false;
    }
    return true;
}

long long nextPrime(long long last_one)
{
    long long next_prime;
    if (last_one == 2)
        next_prime = 3;
    else
        for (next_prime = last_one + 2; !isPrime(next_prime); next_prime += 2);
    return next_prime;
}

void deFactor(long long N)
{
    if (N == 1)
        putchar('\n');
    else
    {
        long long last_try = primeNum[primeNum.size()-1];
        k = 0;
        while (N % last_try != 0)
        {
            last_try = nextPrime(last_try);
            primeNum.push_back(last_try);
        }
        primeNum.push_back(last_try);
        while (N % last_try == 0)
        {
            ++k;
            N /= last_try;
        }
        if (output++)
            putchar('*');
        if (k > 1)
            printf("%lld^%d", last_try, k);
        else
            printf("%lld", last_try);
        deFactor(N);
    }
    return;
}

int main(int argc, char const *argv[])
{
    long long N;
    scanf("%lld", &N);
    printf("%lld=", N);
    if (N == 1)
        printf("1\n");
    else
        deFactor(N);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值