<分区>
在检测范围内的 Kaprekar 数字时,在 C++ 中发现了这个问题。对于号码 77778 -
unsigned long long sq = pow(n, 2);
返回 6,049,417,284 而
unsigned long long sq = n * n;
返回 1,754,449,988
有什么想法吗?这是 pow 避免但正常 n*n 没有的某种溢出吗?
<分区>
在检测范围内的 Kaprekar 数字时,在 C++ 中发现了这个问题。对于号码 77778 -
unsigned long long sq = pow(n, 2);
返回 6,049,417,284 而
unsigned long long sq = n * n;
返回 1,754,449,988
有什么想法吗?这是 pow 避免但正常 n*n 没有的某种溢出吗?
最佳答案
假设您的n
是典型的int
或unsigned int
,这是因为
这一行
unsigned long long sq = n * n;
相当于
unsigned long long sq = (int)(n * n);
因为 n * n 将在将结果分配给 sq 之前首先处理(均为整数)。因此,这是一个溢出问题(欢迎来到Stack Overflow 也是!)。
您可能还想通过搜索来更多地了解这些术语 overflow
和 casting
(因为它们是计算中非常常见的问题,早点理解它们会有很大帮助!)。
这与 Kaprekar 数无关。现在大多数机器 int
都是 32 位的。因此它只能处理值 -2,147,483,648 到 2,147,483,647(或 0 到 4,294,967,295 对于无符号整数计数器部分)。
因此处理 n * n 会得到:
n * n = 6,049,417,284 - 4,294,967,296 = 1,754,449,988 //overflow at (4,294,967,295 + 1)!
如果你事先进行了转换:
unsigned int n = 77778;
unsigned long long sq = pow(n, 2);
unsigned long long sq2 = (unsigned long long)n * n; //note the casting here.
std::cout << sq << std::endl;
std::cout << sq2 << std::endl;
那么结果将是相同的,因为不会有溢出。
关于c++ - C++ 中的平方数,Kaprekar 数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34447435/