函数中查找整数部首的意外行为/错误

Unexpected behaviour/bug in function to find radical of an integer

本文关键字:错误 意外 查找 整数 部首 函数      更新时间:2023-10-16

我写了一个短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)函数并检查错误是否宠物主义者