![](/img/trans.png)
[英]How to eliminate the extra asterisk shown from the prime factorization output?
[英]How to print the middle asterisk shown from the prime factorization output by setting an end condition?
以下代码从用户输入一个 integer (n) 并输出 n 的素数分解。 我正在尝试为这部分代码的 output 设置“结束”条件,但我不能:
if(countA == 1)
cout<<2;
else if(countA != 0)
cout<<2<<"^"<<countA;
正确 output 的示例是:
输入: 100
Output: 2^2*5^2
但它现在打印的是没有中间星号(2 到 5 之间):
2^25^2
整个代码:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n, countA = 0, countB = 0;
cin>>n;
while(n % 2 == 0)
{
n /= 2;
countA++;
}
if(countA == 1)
cout<<2;
else if(countA != 0)
cout<<2<<"^"<<countA;
for(int i = 3, end = sqrt(n); i <= end; i = i + 2)
{
while(n % i == 0)
{
n /= i;
countB++;
}
if(countB == 1)
cout<<i<<"*";
else if(countB != 0)
{
cout<<i<<"^"<< countB;
if(!(i + 1 >= end))
cout<<"*";
}
}
if(n > 2)
cout<<n;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
const char *pad = "";
int main()
{
int n, countA = 0, countB = 0;
cin>>n;
while(n % 2 == 0)
{
n /= 2;
countA++;
}
if(countA > 0)
{
cout<<pad;
cout<<2;
if(countA > 1)
{
cout<<"^"<<countA;
}
pad = "*";
}
for(int i = 3; i <= sqrt(n); i = i + 2)
{
countB = 0;
while(n % i == 0)
{
n /= i;
countB++;
}
if(countB > 0)
{
cout<<pad;
cout<<i;
if(countB > 1)
{
cout<<"^"<<countB;
}
pad = "*";
}
}
if(n > 2)
{
cout<<pad;
cout<<n;
pad = "*";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.