prime factors

题目描述

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1^k1 * p2^k2 *…*pm^km.

输入描述

Each input file contains one test case which gives a positive integer N in the range of long int.

输出描述

Factor N in the format N = p1^k1 * p2^k2 *…*pm^km, where pi’s are prime factors of N in increasing order, and the exponent ki is the number of pi – hence when there is only one pi, ki is 1 and must NOT be printed out.

输入例子

97532468

输出例子

97532468=2^211171011291

解题思路

其实这是一道相对简单的素数因子求解问题。思路是对n进行素因子分解,用的素数x最大到小于sqrt(n)的最大素数xMax。在分解的同时,随着x不断增大,n不断减小,即n/=x。
当x取到xMax时,有两种情况,第一种,此时,n等于1,第二种n>1。
第一种情况,即已经分解完毕。
解释一下第二种情况,n>1,也就是对n进行分解,他的质因数除了分布在2~xMax之间,还有因子分布在(xMax,n]之间,那么这个因子是合数还是质数呢?答案是,一定是质数。为什么呢?

  1. 假如n本身是质数,那么这个因子就是它本身
  2. 假如n是合数,经过前面的分解,此时的n,写作n’,它包含的因子中一定不存在小于xMax的素因子,那么它会不会存在介于(xMax,n’)的质因子呢?假如存在,那么必定还存在一个小于xMax的质因子,矛盾,因此,n’一定不存在小于n’的质因子,即它本身就是它的质因子。
    以下是代码
#include <iostream>
#include<cmath>

using namespace std;

int main(void) {
    long long n;
    while(cin>>n) {
        cout << n << "=";
        if(n==1) {
            cout << 1 << endl;
            continue;
        }
        bool first = true;
        int count;
        for (int i = 2; i <= (int) sqrt(n); i++) {
            count = 0;
            while (n % i == 0) {
                count++;
                n /= i;
            }
            if (count) {
                if (first)
                    first = false;
                else {
                    cout << "*";
                }
                count == 1 ? cout << i : cout << i << "^" << count;
            }
        }
        if (n == 1)
            cout << endl;
        else {
            if(!first)
                cout<<"*";
            cout << n << endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值