PAT甲级A1059 Prime Factors (25 分)

Given any positive integer NNN, you are supposed to find all of its prime factors, and write them in the format NNN = p1k1×p2k2×⋯×pmkm{p_1}^{k_1}\times {p_2}^{k_2} \times \cdots \times {p_m}^{k_m}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 NNN in the range of long int.

Output Specification:

Factor NNN in the format NNN = p1p_1p​1​​^k1k_1k​1​​*p2p_2p​2​​^k2k_2k​2​​**pmp_mp​m​​^kmk_mk​m​​, where pip_ip​i​​'s are prime factors of NNN in increasing order, and the exponent kik_ik​i​​ is the number of pip_ip​i​​ -- hence when there is only one pip_ip​i​​, kik_ik​i​​ is 1 and must NOT be printed out.

Sample Input:

97532468

Sample Output:

97532468=2^2*11*17*101*1291

题意:任意给出一个正整数,让你把它分解成若干个质数相乘的形式,然后按格式输出 。

思路:

1.数学知识:对于任意一个正整数N,可以把它分解成若干个质数相乘,其中因子要么在sqrtN左右两侧成对出现,要么就是sqrtN,并且大于sqrt(N)的因子最多只有一个。

2.可以从2--sqrtN进行遍历,只要n%i==0成立,就令n=n/i;最后如果n==1,说明不存在大于sqrtN的因子,否则仅存在一个。另外1要特殊处理。

参考代码:

#include<cstdio>
#include<cmath>
#include<map>
using namespace std;
int n;
map<int,int> mp;
void getFactor(int n){
	int sqrtN=(int)sqrt(double(n));
	for(int i=2;i<=sqrtN;i++){
		while(n%i==0) {
			n/=i;
			mp[i]++;
		}
	}
	if(n!=1) mp[n]++;
}
int main()
{
	scanf("%d",&n);
	if(n==1) {
		printf("1=1\n");
		return 0;
	}
	getFactor(n);
	printf("%d=",n);
	for(auto it=mp.begin();it!=mp.end();it++){
		if(it!=mp.begin()) printf("*");
		if(it->second==1) 
			printf("%d",it->first);
		else printf("%d^%d",it->first,it->second);
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值