即使我使用%1000000007,它仍然会导致0(Even though I use % 1000000007 it still results on 0 [duplicate])

编程入门 行业动态 更新时间:2024-10-15 16:18:04
使我使用%1000000007,它仍然会导致0(Even though I use % 1000000007 it still results on 0 [duplicate])

我在这个代码上的目标是在没有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 answers

my 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; }

更多推荐

本文发布于:2023-08-07 18:13:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465387.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使我   duplicate   results

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!