函数中查找整数部首的意外行为/错误
Unexpected behaviour/bug in function to find radical of an integer
我写了一个短C++函数,它试图返回类似于整数的根部,而是最小的整数,它是给定数字的某个根。一般逻辑是,该函数将整数分解为素幂,寻找素幂的所有指数的 gcd,然后通过将所有指数除以这个 gcd 来找到根式。我认为该函数按预期工作,但是我注意到当将函数 13 作为参数传递时,它返回 12,我将 2 到 20 的输出放在下面;除了 13 之外,一切都是正确的。当尝试调试时,"素数"和"幂"都保持正确的值(分别为 13 和 1,两个向量的大小均为 1)以及"幂"应该是 1。所以问题一定在最后一个循环中,但我真的对可能发生的情况感到非常困惑,因为它应该计算 pow(13, 1/1)。
#include<vector>
#include<cmath>
int radical(int n){
int power = 0;
std::vector<int> primes;
std::vector<int> powers;
for(int i = 2; n != 1 ; ++i){
int t_pow = 0;
while(n % i == 0){
++t_pow;
n /= i;
}
if(t_pow != 0){
primes.push_back(i);
powers.push_back(t_pow);
}
power = (power == 0 ? t_pow : gcd(power, t_pow));
}
int rad = 1;
for(unsigned i = 0u; i < primes.size(); ++i){
rad *= pow(primes.at(i), powers.at(i)/power);
}
return rad;
}
22
33
4 2
55
66
77
8 2
9 3
1010
11 11
12 12
13 12
14 14
15 15
16 2
1717
18 18
19 19
2020
编辑:实现基于整数的幂函数pow(int,int)的最有效方法
朴素算法实际上看起来很简单:
rad = 1
i = 1
While n > 1:
increase i
if i divides n:
multiply rad by i
while i divides n, divide n by i
您已经在执行所有这些步骤,事实是您正在执行更多(并且使用更多空间),那么为什么不摆脱不必要的操作呢?
定义自己的int powi(int,int)
函数并检查错误是否宠物主义者
相关文章:
- vscode下的Arduino代码出现意外编译错误
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- C++标头错误 C2238 意外标记";"
- C++ 编译错误:意外的类型名称"字符串":预期的表达式
- 在gcc中意外调用了Const重载.编译器错误或兼容性修复程序
- "错误 C0000:语法错误,令牌"<EOF>"处出现意外$end,并且不确定
- boost::p rogram_options 在指定意外的位置参数时不报告任何错误
- 从 C++ 调用 cURL 命令会返回意外的错误代码,如 1792 和 6656
- Qt5 C++中出现意外"Multiple definition"错误
- 排序程序的意外错误代码
- 在 c++ 中声明向量时出现意外错误
- 函数调用中出现意外编译错误 (C++)
- 使用相同的函数时意外收到"std::out_of_range"错误
- 在第三个 pary 函数中使用矢量引用时出现意外错误
- 创建进程失败,意外错误
- 企业架构师错误:意外符号修复
- 在 Linux C++的两个线程之间使用管道的错误/意外行为
- Mex运行时错误:意外的标准表达式
- Cmake 奇怪的错误:语法错误意外的令牌 ('
- Cuda错误:意外启动失败