【发布时间】:2017-02-02 15:47:40
【问题描述】:
problem statement 要求我找出 a^b 的最后一位数字。 约束条件是 0
我的代码对于 12^8 或 6^9 或类似的数字非常有效。 但是当我移动到大数区域时,比如 14^1234 或 17^148713,我总是得到 -8 的输出。
#include <stdio.h>
#include <math.h>
int main() {
int t;
scanf("%d", &t);
while(t--)
{
int a;
long long int b;
double x, y, res;
scanf("%d %lld", &a, &b);
x=(double)a;
y=(double)b;
res = pow(x, y);
int rem;
rem = (int)res%10;
printf("%d\n", rem);
}
return 0; }
这种奇怪的输出可能是什么原因?
除了将大数字存储在数组中之外,没有其他办法了吗(我猜是How to calculate 2 to the power 10000000)?
【问题讨论】:
-
您需要一个更好的算法 - 多考虑底层数学,而不是仅仅尝试使用蛮力。
-
对于您当前的解决方案,浮点数的精度远远受限。
-
提示:阅读Modular exponentiation。
-
您应该检查系统上
DBL_MAX的值,这是在<floats.h>中定义的常量。奇怪的是,它比您要处理的数字小很多数量级。 -
至于 -8,一旦
res变为无限,将其转换为int会产生 未定义的行为,如 What is the result of casting float +INF, -INF, and NAN to integer in C? 中所述。在我的机器上,演员表的结果是 0x80000000 或 -2,147,483,648。那个数字 mod 10 是 -8。
标签: c exponentiation