1059 Prime Factors (25分)+一个简洁的写法

问题

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^211171011291

解决方法

分析:素数表的建立。
题⽬⼤意:给出⼀个整数,按照从⼩到⼤的顺序输出其分解为质因数的乘法算式。

#include<iostream>
#include<math.h>
#include<map>
using namespace std;
int main()
{
	int n;
	map<int, int>m;
	scanf("%d", &n);
	printf("%d=", n);
	if (n == 1)
	{
		printf("1\n");
		return 0;
	}
	for (int i = 2; i <= sqrt(n); i++)
	{
		while (n%i == 0)
		{
			m[i]++;
			n = n / i;
		}
	}
	if (n > 1) m[n]++;
	for (auto it = m.begin(); it != m.end(); it++)
	{
		it == m.begin() ? printf("%d", it->first) : printf("*%d", it->first);
		if(it->second>1) printf("^%d", it->second);
	}
	return 0;
}

后记

这个题最开始读题不仔细,走了很多的弯路,所以读题一定要认真。。。o(╥﹏╥)o其实内心想把自己拍死。

发布了240 篇原创文章 · 获赞 3 · 访问量 4934
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览