我在这个代码上的目标是在没有pow()的情况下进行指数运算。 它适用于evey值a ^ b,其中b <= 30。我知道我应该使用x%1000000007来防止整数溢出。
#include <stdio.h> int main(void) { int i, a, b, rst; rst = 1; scanf("%d %d", &a, &b); for (i = 0; i < b; i++){ rst = rst * a; if( b == 0){ rst = 1; } } printf("%d\n", rst % 1000000007); return 0; }为什么它会在“2 ^ 40%1000000007”上返回“0”,即使我正在使用%1000000007?
This question already has an answer here:
Need help in mod 1000000007 questions 3 answersmy goal on this code is to make exponential operations without pow(). It works for evey value a^b which b <= 30. I'm aware that I should be using x % 1000000007 to prevent integers overflows.
#include <stdio.h> int main(void) { int i, a, b, rst; rst = 1; scanf("%d %d", &a, &b); for (i = 0; i < b; i++){ rst = rst * a; if( b == 0){ rst = 1; } } printf("%d\n", rst % 1000000007); return 0; }Why does it returns a "0" for example on "2^40 % 1000000007" even though I'm using % 1000000007?
最满意答案
首先 ,你不需要for循环中的if语句。 其次 ,你试图在已经发生之后停止整数溢出。 所以你需要在每次乘法运算后进行。 第三 ,你可以使用unsigned long long int而不是int ,因为int是依赖于机器的(可能是1000000007对于你的机器来说太大了)。
我想这应该工作:
#include <stdio.h> int main() { unsigned long long int i, a, b, rst; scanf("%llu %llu", &a, &b); rst = 1; for (i = 0; i < b; i++){ rst = (rst * a) % 1000000007; } printf("%llu\n", rst); return 0; }First, you don't need if statement in for loop. Second, you are trying to stop integer overflow after it already happens. So you need to do it after every multiplication operation. Third, you can use unsigned long long int instead of int, because int is machine dependent (may be 1000000007 is too big for int on your machine).
I guess this should work:
#include <stdio.h> int main() { unsigned long long int i, a, b, rst; scanf("%llu %llu", &a, &b); rst = 1; for (i = 0; i < b; i++){ rst = (rst * a) % 1000000007; } printf("%llu\n", rst); return 0; }更多推荐
发布评论