Math.pow(65,17)%3233令人惊讶的结果 [英] Surprising result from Math.pow(65,17) % 3233

查看:314
本文介绍了Math.pow(65,17)%3233令人惊讶的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因处理大数字,模数运算符不给我正确的输出,看看代码

For some reason when dealing with large numbers, the modulus operator doesnt give me the correct output, have a look at the code

double x = Math.pow(65,17) % 3233;

输出应为 2790
但输出是 887.0

我确信它的东西很愚蠢,但我无法解决。感谢提前

I am sure its something silly but i cant get around it. Thanks in advance

推荐答案

Math.pow(65,17)不能正确地表示为 double ,并且正在四舍五入到最接近的数字。

The result of Math.pow(65, 17) cannot be represented exactly as a double, and is getting rounded to the nearest number that can.

pow(a,b)%c 操作称为模幂运算。 维基百科页面包含了许多关于如何计算它的想法。

The pow(a, b) % c operation is called "modular exponentiation". The Wikipedia page contains lots of ideas for how you might go about computing it.

这是一种可能性:

public static int powmod(int base, int exponent, int modulus) {
    if (exponent < 0)
        throw new IllegalArgumentException("exponent < 0");
    int result = 1;
    while (exponent > 0) {
        if ((exponent & 1) != 0) {
            result = (result * base) % modulus;
        }
        exponent >>>= 1;
        base = (base * base) % modulus;
    }
    return result;
}

这篇关于Math.pow(65,17)%3233令人惊讶的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆