简体   繁体   English

处理双打时的模运算符用法

[英]Modulo operator usage while dealing with doubles

I have to find the value of ( 1+sqrt(3) )^n where n < 10^9.As this number can be very large we have to print the ans%1000000007. 我必须找到(1 + sqrt(3))^ n的值,其中n <10 ^ 9。由于这个数字可能非常大,我们必须打印ans%1000000007。 I have written the following function for this. 我为此编写了以下函数。

double power(double x, int y)
{
    double temp;
    if( y == 0)
       return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
       return temp*temp;
    else
    {
       if(y > 0)
           return x*temp*temp;
       else
           return (temp*temp)/x;
    }
}

Now, I unable to understand how to take care of the modulo condition.Can somebody please help. 现在,我无法理解如何处理模态。请有人帮忙。

You can't do that. 你不能那样做。 You could use fmod , but since sqrt(3) cannot be exactly represented, you'd get bogus values for large exponents. 您可以使用fmod ,但是由于无法精确表示sqrt(3)因此对于大指数,您会得到假值。

I'm rather confident that you actually need integer results ( (1 + sqrt(3))^n + (1 - sqrt(3))^n ), so you should use integer math, exponentiation by squaring with a modulo operation at each step. 我非常有信心,您实际上需要整数结果( (1 + sqrt(3))^n + (1 - sqrt(3))^n ),因此您应该使用整数数学,并通过对模运算求平方来求幂每一步。 cf. cf. this question 这个问题

This approach is infeasible. 这种方法是不可行的。 As shown in this question , you would need hundreds of millions of decimal digits more precision than the double type supplies. 如此问题所示,您需要比双精度类型提供的精度高数亿个十进制数字。 The problem you are actually trying to solve is discussed here . 你实际上是试图解决的问题进行了讨论这里 Are you two in the same class? 你们两个在同一班吗?

模数需要整数类型,您可以将union用作双精度类型,并与整数结合使用模数(如果这是C)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM