1059 Prime Factors (25 分)

本文详细解析了1059PrimeFactors问题,探讨了如何找出任意正整数的所有质因数,并按照质因数的升序及次数输出。通过实例演示了解题过程,包括特殊情况的处理,如当输入为1时的考量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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​2k2>​×⋯×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^km, where p​i’s are prime factors of N in increasing order, and the exponent ki is the number of pi – 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^2*11*17*101*1291
分析

本题考查素数,解题方法很多,此题解法是若n能整除i则将n中所有的i因子在本次大循环中全部提取出来,然后判断k>=1,若成立表示i是n的因子,然后分别对k=1和k>1的情况进行输出,每次统计完一个因子后将k清零,用于下一次统计,同时将i++,移向下一个因子(若下一个因子是合数,程序是直接跳过的,因为合数可以分解为前面多个素数之积),博客1的解法是先建立素数表,在整除n时直接查找素数,两种解法时间复杂度相等。
注:做素数相关的题时,需要留意正整数1是否进行了考查,因为往往题目对N的描述是positive integer,这是包含1的,尽管1既不是素数又不是合数,也尽管题目要求输出的是prime factors,似乎题面和标准答案自相矛盾(一方面说考虑素数因子,一方面隐含得分点要求考虑非素数的1),但是总之遇到这类题就提个醒儿~不管题目怎么表述,先考虑1的情况吧~,因为99.99999%的情况正整数1是隐藏得分点,本题测试点3(index from 0)考查的就是这个。

#include <iostream>
using namespace std;
int main(){
	FILE * f=fopen("demo","w");
	long int n;
	cin>>n;
	if(n==1) {
		printf("1=1");
		return 0;
	}
	printf("%ld=",n);
	long int k=0,i=2;
	bool first=true;	
	while(n!=1){
		while(n%i==0){
			k++;
			n/=i;
		}
		if(k>=1){
			if(first) {
				first=false;
			}else printf("*");
			printf("%ld",i);
			if(k>1) printf("^%ld",k);
		}
		k=0;
		i++;
	}
	return 0;
}

  1. https://www.liuchuo.net/archives/2289 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值