gpt4 book ai didi

c++ - 以幂形式打印整数的素因数 ( ^ )

转载 作者:行者123 更新时间:2023-11-30 21:31:07 25 4
gpt4 key购买 nike

我需要一个 C++ 或 C 程序来计算素因数,例如您输入 135 我希望输出像这样 (3^3)(5^1) 而不是 3,3,3,5。

#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
void get_divisors(int n);
int main()
{
int n = 0;
cout << "Enter a number:";
cin >> n;
get_divisors(n);
cout << endl;
}
void get_divisors(int n)
{
int i;
double sqrt_of_n = sqrt(n);
for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0)
{
cout << i << ", ";
get_divisors(n / i);
return;
}
cout << n;
}

最佳答案

使用std::map<int, int>包含素数(第一个整数)和该素数出现的次数(第二个整数)。

因此,当您有素数时,请在映射中查找该值,如果映射中没有,则将其插入。

如果素数已经存在,则增加计数。

打印时,您会迭代映射,打印素数,然后打印“^”字符,然后打印素数的计数。

详细信息留给读者作为练习。

关于c++ - 以幂形式打印整数的素因数 ( ^ ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19031457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com