甲级PATA1059 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.

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 

这道题的大意是输入一个数,把他进行质因子分解并按格式输出。


为了方便解题,首先我们得了解一些数学知识:


1.对于正整数N,如果存在不同于1和它自身的因数,那么因数要么等于sqrt(N)(N的平方根),要么在sqrt(N)的左右成对出现。


2.对于正整数N,把它因式分解,要么所有的质因子都小于等于sqrt(N),要么只存在一个质因子大于sqrt(N),其余质因子全小于sqrt(N)。


所以我们可以让i从2-sqrt(N)开始枚举,如果N能整除,那么把该因子记录下来,同时该因子的数目+1,N=N/i。

如果过程结束后N不等于1,那么现在的N就是唯一一个大于sqrt(N)的质因子,也记录下来,令他的数目为1.

注意1是特殊情况,要特殊处理。

源代码如下:

#include<cstdio>
#include<cmath>

struct factor {
	int x;//质因子
	int cnt;//该质因子的个数
}fac[10];

long long N;

int factorNum = 0;//表示第几个质因数,如2可能是第一个质因数,3可能是第二个质因数

//求出数N的所有质因子,并保存在结构体fac中
void getFactor(long long num) {
	if (num == 1) {
		fac[0].x = 1;
               return;
	}
	double sqr = sqrt(num);
	for (long long i = 2; i <= sqr; ++i) {
		if (num%i == 0) {
			fac[factorNum].x = i;
			fac[factorNum].cnt = 0;
			while (num%i == 0) {
				fac[factorNum].cnt++;
				num /= i;
			}
			factorNum++;
		}
	}
	if (num != 1) {
		fac[factorNum].x = num;
		fac[factorNum].cnt = 1;
	}
}

int main(){

	scanf("%lld", &N);
	getFactor(N);
	
	//输出结果
	printf("%lld=", N);
	if (factorNum == 0) {
		printf("%d", fac[0].x);
	}
	else {
		for (int i = 0; i < factorNum; ++i) {
			printf("%d", fac[i].x);
			if (fac[i].cnt != 1) printf("^%d", fac[i].cnt);
			if (i != factorNum - 1) printf("*");
		}
	}
	
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值