使用fmod和自己的实现的math.h库 [英] Library math.h using fmod and own implementation

查看:119
本文介绍了使用fmod和自己的实现的math.h库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//test.cpp
fmod( pow(2.0,127),467 );// Return result as 132 <-- correct answer

当我使用自己的实现方式

When i using my own implementation

int mod( int dividend , int divisor ){
return (dividend % divisor + divisor ) % divisor;
}

int a = mod ( pow(2.0,127),467 );// Wrong result , 441

//or direct use
int a = pow(2.0,127);
int b = a%467 // Will return wrong result , -21

我想获得答案132,fmod可以,但是为什么我的实现无法获得正确的答案?

i want to get answer 132, fmod does it, but why my implementation cannot get the correct answer?

推荐答案

伊万(Ivan)解决的问题是,您超出了整数的范围.不幸的是,没有可以容纳2 ^ 127的本机类型(不包括使用两个64位结果作为合成的128位int).

The problem, as addressed by Ivan, is that you are exceeding the bounds of an integer. Unfortunately there is no native type which can hold 2^127 (Excluding using two 64 bit results as a synthetic 128 bit int).

但是,幸运的是,在这种情况下,您更可能想要的是powmod. Powmod是一个pow函数,可以与功率同时计算mod(顾名思义).这样的事情应该为您解决问题:

However, fortunately for you, in this case you more likely what you want is powmod. Powmod is a pow function which computes mod at the same time as the power (as the name would suggest). Something like this should do the trick for you:

int powmod(int b, int e, int m)
{
    int result = 1;
    while(e > 0){
        if(e & 1){
            result *= b;
            result %= m;
        }
        b *= b;
        b %= m;
        e >>= 1;
    }
    return result;
}

在这种情况下,b是您的底数,e是您的指数,m是您的mod.因此,在这种情况下,powmod(2, 127, 467)返回132-您想要的答案.希望这会有所帮助,如果您要处理大量数字和模块化算术,建议您阅读一两篇有关模块化运算的一致性的文章.

In this case, b is your base, e is your exponent, and m is your mod. So in this case powmod(2, 127, 467) returns 132 -- your intended answer. Hope this helps, and if you're dealing with a lot of big numbers and modular arithmetic I suggest you read an article or two on congruency of modular operations.

修复了语法错字.

这篇关于使用fmod和自己的实现的math.h库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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