如何消除素数分解输出中显示的额外星号?
How to eliminate the extra asterisk shown from the prime factorization output?
以下代码从用户输入一个整数 (n) 并输出 n 的素数分解。我需要有以下输出(作为示例),但无法达到:
输入:98
输出:2*7^2
实际错误的输出,多了一个“*”是:
2*7^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; i <= sqrt(n); i = i + 2)
{
while(n % i == 0)
{
n /= i;
countB++;
}
if(countB == 1)
cout<<i<<"*";
else if(countB != 0)
cout<<i<<"^"<<countB<<"*";
}
if(n > 2)
cout<<n;
return 0;
}
而不是无条件地打印它:
cout<<i<<"^"<<countB<<"*";
您可以测试它是否是最后一个数字。示例(在需要的地方应用):
for(int i = 3, end = sqrt(n); i <= end; i = i + 2) {
// ...
cout << i << '^' << countB;
if(i + 2 <= end) cout << '*';
根据@Jonathan Leffler 的评论,我的问题的可能解决方案之一如下:
#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;
}
以下代码从用户输入一个整数 (n) 并输出 n 的素数分解。我需要有以下输出(作为示例),但无法达到:
输入:98
输出:2*7^2
实际错误的输出,多了一个“*”是:
2*7^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; i <= sqrt(n); i = i + 2)
{
while(n % i == 0)
{
n /= i;
countB++;
}
if(countB == 1)
cout<<i<<"*";
else if(countB != 0)
cout<<i<<"^"<<countB<<"*";
}
if(n > 2)
cout<<n;
return 0;
}
而不是无条件地打印它:
cout<<i<<"^"<<countB<<"*";
您可以测试它是否是最后一个数字。示例(在需要的地方应用):
for(int i = 3, end = sqrt(n); i <= end; i = i + 2) {
// ...
cout << i << '^' << countB;
if(i + 2 <= end) cout << '*';
根据@Jonathan Leffler 的评论,我的问题的可能解决方案之一如下:
#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;
}