【PAT】【Advanced Level】1059. Prime Factors (25)

1059. Prime Factors (25)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
HE, Qinming

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.

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 = 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.

Sample Input:
97532468
Sample Output:
97532468=2^2*11*17*101*1291
原题链接:

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

https://www.nowcoder.com/pat/5/problem/4112

思路:

对于每一个数进行扫描,从2开始,每找到一个因子,不断相除,累加该因子次数。

——PAT AC,牛客网超时

对于每个数先判断是否是质数,如果是则不用再分解

——AC

CODE:

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
typedef struct S
{
	int nu;
	int p;
};
vector<S> pri;
bool pr(int n)
{
	if (n==1||n==2||n==3) return 1;
	for (int i=2;i*i<=n;i++)
	 	if (n%i==0) return 0;
	return 1;
}
int main()
{
	int n;
	cin>>n;
	cout<<n<<"=";
	if (pr(n))
	{ 
		cout<<n; 
	}
	else
	{
		int i=2;
		while (i<=n)
		{
			if (n%i==0)
			{
				S t;
				t.nu=i;
				t.p=0;
				while (n%i==0)
				{
					t.p++;
					n/=i;
				}
				pri.push_back(t);
			}
			i++;
		}
		for (int i=0;i<pri.size()-1;i++)
		{
			cout<<pri[i].nu;
			if (pri[i].p!=1)
			{
				cout<<"^"<<pri[i].p; 
			}
			cout<<"*";
		}
		cout<<pri[pri.size()-1].nu;
		if (pri[pri.size()-1].p!=1)
		{
			cout<<"^"<<pri[pri.size()-1].p; 
		}
	}
	return 0;
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值