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

被折叠的 条评论
为什么被折叠?



