浙江大学PAT_甲级_1059. Prime Factors (25)

本文介绍了一种使用C++编程语言的方法来找出任意正整数的所有质因数,并将它们以特定格式输出。通过实现一个高效的算法,该文章详细解释了如何进行质数判断、质因数分解以及如何将最终结果以数学表达式的形式呈现。此教程适合希望提高其C++编程技巧或对数论感兴趣的学习者。

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

题目链接:点击打开链接

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
我的C++代码:

#include<iostream>
#include<cmath>
using namespace std;
bool prime(int value)//若value是素数,返回1,不是返回0.
{
	int i = 2;
	if (value == 0 || value == 1)//素数是一个大于1的自然数,不包括0 1
	{
		return false;
	}
	for (; i <= sqrt(value); i++)
	{
		if (value%i == 0)
		{
			return false;
		}
	}
	return true;
}
int main()
{
	int i=0,n;
	cin >> n;
	cout << n << "=";
	if (n==1)
	{
		cout <<n;
	}
	else
	{
		for (i = 2; i <= n; i++)
		{
			int exp = 0;//因子的指数
			if (prime(i))//因子是素数
			{
				while (n%i == 0)//分解求指数
				{
					exp++;
					n = n / i;
				}
			}
			if (exp >= 2)//输出指数>=2的因子及指数
				cout <<i<< "^" << exp;
			else if (exp==1)//指数等于1只输出因子
				cout <<i;
			if (n != 1 && exp >= 1)//exp >= 1表示有素因子时才输出*号
				cout << '*';
			else if (n == 1)//全部分解,退出
				break;
		}
	}
	//system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值