PAT A1059 质因子分解

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

大意是将一个long int型整数进行质因子分解

解题思路:

1.打质数表

2.将所给整数m按照质数表从小到大的顺序相除,每个质数都除到不能除为止,用结构体记录相应质数和除的次数

3.输出

坑:

1.等于1的时候是特例,得特殊处理

2.注意最后得到的1不能输出


代码(long long和int用混了,不管了反正ac了)

#include<cmath>
#include<time.h>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;

typedef long long LL;
#define MAX 100000000

LL prime[10000];
int count = 0;
bool is_prime[MAX] = {0};

void get_prime(int maxn){
	memset(is_prime,0,sizeof(bool)*maxn);
	for(int i=2;i<maxn;i++){
		if(!is_prime[i]){
			prime[count++] = i;
			for(int j=i+i;j<maxn;j += i){
				is_prime[j] = true;
			}
		}
	}
}

int main(){
	LL mm,m;
	scanf("%lld",&mm);
	if(mm == 1){
		printf("1=1");
		return 0;
	}
	m = mm;
	LL m_sqrt = sqrt(m*1.0);
	get_prime(m_sqrt);

	struct ans{
		LL prime;
		int num;
	}ans[10];
	
	int ans_c = 0;
	LL i=0;
	while(i<count){
		if(m%prime[i]==0){
			ans[ans_c].prime = prime[i];
			ans[ans_c].num = 1;
			m = m/prime[i];
			while(m%prime[i]==0){
				m = m/prime[i];
				ans[ans_c].num++;
			}
			ans_c++;
		}
		i++;
	}
	if(m!=1){
		ans[ans_c].prime = m;
		ans[ans_c++].num = 1;
	}
	printf("%lld=",mm);
	for(i=0;i<ans_c;i++){
		if(i>0) printf("*");
		if(ans[i].num!=0){
			if(ans[i].num == 1){
				printf("%lld",ans[i].prime);
			}else{
				printf("%lld^%d",ans[i].prime,ans[i].num);
			}
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值